混淆ls命令,该命令列出目录的绝对路径

时间:2019-10-17 05:09:18

标签: linux bash glob

我在线找到了列出当前目录中所有目录的绝对路径的代码:

  

ls -d“ $ PWD” / *

代码按预期工作,但是我对代码的工作方式以及最后的“ / *”功能感到困惑。

1 个答案:

答案 0 :(得分:1)

首先,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"*的{​​{1}}也匹配/之类的路径,不仅匹配目录/home/anthony1内的文件。

相关问题