我在网上找到了代码,列出了当前目录下所有目录的绝对路径:
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/