我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。

最有效的写法是什么?


当前回答

找到。-type d -print0 | xargs -0 -n 1 my_command

其他回答

避免创建子进程的版本:

for D in *; do
    if [ -d "${D}" ]; then
        echo "${D}"   # your processing here
    fi
done

或者,如果你的操作是一个单一的命令,这是更简洁的:

for D in *; do [ -d "${D}" ] && my_command; done

或者一个更简洁的版本(感谢@enzotib)。注意,在这个版本中,每个D的值都有一个尾随斜杠:

for D in */; do my_command; done

如果你想在文件夹内而不是在文件夹上执行操作。

说明:您有许多pdf文件,希望将它们集中在一个文件夹中。 我的文件夹

   AV 001/
   AV 002/

for D in *; do cd "$D"; # VERY DANGEROUS COMMAND - DONT USE #-- missing "", it will list files too. It can go up too. for d in */; do cd "$d"; echo $d; cd ..; done; # works succesfully for D in "$(ls -d */)"; do cd "$D"; done; # bash: cd: $'Athens Voice 001/\nAthens Voice 002/' - there is no such folder for D in "$(*/)"; do cd "$D"; done; # bash: Athens Voice 001/: is folder for D in "$(`find . -type d`)"; do cd $D; done; # bash: ./Athens: there is no such folder or file for D in *; do if [ -d "${D}" ] then cd ${D}; done; # many arguments

如果目录名中有空格,则接受的答案将在空格上中断,对于bash/ksh,首选语法是$()。使用GNU find -exec选项+;如

找到……- mycommand +;#这和传递给xargs是一样的

或者使用while循环

find .... | while read -r D
do
    # use variable `D` or whatever variable name you defined instead here
done 

这将创建一个子shell(这意味着当while循环退出时,变量值将丢失):

find . -type d | while read -r dir
do
    something
done

这不会:

while read -r dir
do
    something
done < <(find . -type d)

如果目录名中有空格,这两种方法都可以工作。

找到。-type d -print0 | xargs -0 -n 1 my_command