shell - 测试 -d 目录 true - 子目录 false (POSIX)

标签 shell unix testing directory posix

我正在尝试打印给定起始目录中的所有目录/子目录。

for i in $(ls -A -R -p); do 
    if [ -d "$i" ]; then
            printf "%s/%s \n" "$PWD" "$i"
    fi
done; 

此脚本返回在 .目录和该目录中的所有文件,但由于某种原因,子目录的测试失败。所有目录都以 $i 结尾,输出看起来完全一样。
假设我有以下结构:

foo/bar/test

echo $i 打印

foo/
bar/
test/

虽然文件夹的内容是这样列出的:

./foo:
file1
file2
./bar:
file1
file2

但是测试语句只打印:

PWD/TO/THIS/DIRECTORY/foo

出于某种原因,它对第一级目录返回 true,但对所有子目录返回 false。

(ls 可能不是执行此操作的好方法,如果 find 语句可以解决我所有的问题,我会很高兴,但首先我想知道为什么这个脚本不能像您想象的那样工作。 )

最佳答案

正如评论中指出的那样,问题在于目录名称包含 :,因此 -d 为 false。

我猜这个命令会给你想要的输出(尽管它需要 Bash):

# enable globstar for ** 
# disabled in non-interactive shell (e.g. a script)
shopt -s globstar 

# print each path ending in a / (all directories)
# ** expands recursively
printf '%s\n' **/*/

标准方法要么自己进行递归,要么使用find:

find . -type d

关于shell - 测试 -d 目录 true - 子目录 false (POSIX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50025587/

相关文章:

unit-testing - 单元测试与验收测试

mysql - Shell - 使用包含双引号的字符串变量

c - 如何将 execvp 结果作为字符串存储在 char 数组中

shell - C shell : How to execute a program with non-command line arguments?

python - 使用 Python os 模块获取 unix 文件类型

testing - 使用 Travis CI 进行 Flutter 集成测试

linux - 如何将文件从 windows 复制到 linux(跨平台)?

unix - `-h` 中的 `ls -lah` 在 Unix 中如何工作?

python - 国际化 Django(在 OSX 上)

reactjs - Jest - 无法从 'source-map' 找到模块 'source-map-support.js'