linux - 对列出目录绝对路径的 ls 命令感到困惑

标签 linux bash glob

我在网上找到了代码,列出了当前目录下所有目录的绝对路径:

ls -d "$PWD"/*

代码按预期工作,但我对它的工作原理和末尾“/*”的功能感到困惑。

最佳答案

首先,ls -d不仅仅列出当前目录中所有目录的绝对路径。它还列出非目录。 -d 告诉 ls 不要列出目录的内容。 -d 不会告诉 ls 排除文件。例如,假设当前目录包含一个名为“dir”的目录,“dir”包含三个文件:

ls dir
# output:
file1 file2 file3

ls -d dir
# output:
dir

ls -d dir/*
# output:
file1 file2 file3

如果您只想查找目录,请尝试find "$PWD"/* -type d(包括子目录)或find "$PWD"/* -maxdepth 0 -type d(不包括子目录)。

"$PWD"/* 怎么样? PWD 是一个变量,其值为当前工作目录。因此,如果您位于 /home/anthony,则 PWD 的值为 /home/anthony$PWD 告诉 bash 使用 PWD 的值,因此输入 $PWD/* 或多或少相当于输入 /home/anthony/*

"$PWD"/* 中的双引号怎么样?如果当前目录的路径包含有问题的字符(例如空格),则存在这些字符。例如,假设工作目录是 /home/anthony/My Documents:

ls $PWD
# output:
ls: cannot access '/home/anthony/My': No such file or directory
ls: cannot access 'Documents': No such file or directory

ls "$PWD"
# output:
file1 file2 etc...

"$PWD"/* 中的 / 怎么样?不带 /"$PWD"* 也匹配 /home/anthony1 等路径,而不仅仅是目录 /home/anthony 内的文件。

关于linux - 对列出目录绝对路径的 ls 命令感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425268/

相关文章:

bash - 通配 : Matching files names with a number in a script?

Linux - 如何将 file1.txt 的全部内容插入到 file2.txt 的第 4 行

linux - 尝试编辑 crontab 时光标不向右移动

c# - 客户端证书 HttpClient .Net Core Docker Linux

更改堆栈空间

linux - 删除特定扩展文件格式以外的文件

bash - 我刚刚分配了一个变量,但 echo $variable 显示了其他内容

powershell - 如何使用 Invoke-WebRequest 的 -OutFile 参数转义文件路径中的方括号

bash - 为什么 zsh 会尝试扩展 * 而 bash 不会?

linux - grep awk 忽略字符