我正在 Linux 上用 bash 编写脚本,需要遍历给定目录中的所有子目录名称。如何遍历这些目录(并跳过常规文件)?
例如:
给定目录是 /tmp/
它有以下子目录: /tmp/A, /tmp/B, /tmp/C
我想检索 A、B、C。
原文由 Erik Sapir 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在 Linux 上用 bash 编写脚本,需要遍历给定目录中的所有子目录名称。如何遍历这些目录(并跳过常规文件)?
例如:
给定目录是 /tmp/
它有以下子目录: /tmp/A, /tmp/B, /tmp/C
我想检索 A、B、C。
原文由 Erik Sapir 发布,翻译遵循 CC BY-SA 4.0 许可协议
到目前为止,所有答案都使用 find
,所以这里只有一个外壳。在您的情况下不需要外部工具:
for dir in /tmp/*/ # list directories in the form "/tmp/dirname/"
do
dir=${dir%*/} # remove the trailing "/"
echo "${dir##*/}" # print everything after the final "/"
done
原文由 ghostdog74 发布,翻译遵循 CC BY-SA 4.0 许可协议
7 回答5.3k 阅读
4 回答4k 阅读
2 回答5.9k 阅读✓ 已解决
2 回答2.5k 阅读✓ 已解决
1 回答2.3k 阅读✓ 已解决
2 回答794 阅读✓ 已解决
2 回答3.2k 阅读
一个简短的解释:
find
找到文件(很明显).
is the current directory, which after thecd
is/tmp
(IMHO this is more flexible than having/tmp
directly in thefind
命令。如果您想在此文件夹中执行更多操作,您只有一个地方cd
可以更改)-maxdepth 1
and-mindepth 1
make sure thatfind
only looks in the current directory and doesn’t include.
itself in the result-type d
仅查找目录-printf '%f\n
只打印每次点击找到的文件夹的名称(加上换行符)。瞧!