如何在 Linux 中循环目录? [英] How to loop over directories in Linux?
问题描述
我正在 Linux 上用 bash 编写脚本,需要遍历给定目录中的所有子目录名称.如何遍历这些目录(并跳过常规文件)?
I am writing a script in bash on Linux and need to go through all subdirectory names in a given directory. How can I loop through these directories (and skip regular files)?
例如:
给定的目录是 /tmp/
它有以下子目录:/tmp/A、/tmp/B、/tmp/C
我想检索 A、B、C.
I want to retrieve A, B, C.
推荐答案
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f
'
简短说明:
find
查找文件(很明显)
.
是当前目录,在 cd
之后是 /tmp
(恕我直言,这比 /tmp
直接在 find
命令中.如果您希望在此文件夹中执行更多操作,您只有一个位置 cd
可以更改)
.
is the current directory, which after the cd
is /tmp
(IMHO this is more flexible than having /tmp
directly in the find
command. You have only one place, the cd
, to change, if you want more actions to take place in this folder)
-maxdepth 1
和 -mindepth 1
确保 find
只查找当前目录,不包括 .
本身在结果中
-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
只为每次点击打印找到的文件夹的名称(加上换行符).
-printf '%f
prints only the found folder's name (plus a newline) for each hit.
等等!
这篇关于如何在 Linux 中循环目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!