如何在 Linux 中遍历目录?

新手上路,请多包涵

我正在 Linux 上用 bash 编写脚本,需要遍历给定目录中的所有子目录名称。如何遍历这些目录(并跳过常规文件)?

例如:

给定目录是 /tmp/

它有以下子目录: /tmp/A, /tmp/B, /tmp/C

我想检索 A、B、C。

原文由 Erik Sapir 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 567
2 个回答
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'

一个简短的解释:

  • find 找到文件(很明显)

  • . is the current directory, which after the cd is /tmp (IMHO this is more flexible than having /tmp directly in the find 命令。如果您想在此文件夹中执行更多操作,您只有一个地方 cd 可以更改)

  • -maxdepth 1 and -mindepth 1 make sure that find only looks in the current directory and doesn’t include . itself in the result

  • -type d 仅查找目录

  • -printf '%f\n 只打印每次点击找到的文件夹的名称(加上换行符)。

瞧!

原文由 Boldewyn 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题