Bash脚本 - 迭代find的输出

Nat*_*ara 1 linux bash shell scripting

我有一个bash脚本,我需要遍历find命令的输出的每一行,但看起来我正在从find命令迭代每个Word(空格分隔).到目前为止我的脚本看起来像这样:

folders=`find -maxdepth 1 -type d`

for $i in $folders
do
    echo $i
done
Run Code Online (Sandbox Code Playgroud)

我希望这会给出如下输出:

./dir1 and foo
./dir2 and bar
./dir3 and baz
Run Code Online (Sandbox Code Playgroud)

但我得到这样的输出:

./dir1
and
foo
./dir2
and
bar
./dir3
and
baz
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Cha*_*ffy 16

folders=`foo`
Run Code Online (Sandbox Code Playgroud)

总是错的,因为它假定你的目录不包含空格,换行符(是的,它们是有效的!),glob字符等.一个强大的方法(需要GNU扩展-print0)如下:

while IFS='' read -r -d '' filename; do
  : # something with "$filename"
done < <(find . -maxdepth 1 -type d -print0)
Run Code Online (Sandbox Code Playgroud)

另一种安全可靠的方法是让find自己直接调用所需的命令:

find . -maxdepth 1 -type d -exec printf '%s\n' '{}' +
Run Code Online (Sandbox Code Playgroud)

有关该主题的完整处理,请参阅UsingFind wiki页面.


che*_*ner 5

由于您没有使用任何更高级的功能find,因此可以使用简单模式迭代子目录:

for i in ./*/; do
    echo "$i"
done
Run Code Online (Sandbox Code Playgroud)