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

问题描述 投票:0回答:1

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

ls -d“ $ PWD” / *

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

linux bash glob
1个回答
0
投票

首先,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...
© www.soinside.com 2019 - 2024. All rights reserved.