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

最有效的写法是什么?


当前回答

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

其他回答

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

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

这不会:

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

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

如果目录名中有空格,则接受的答案将在空格上中断,对于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 

避免创建子进程的版本:

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
for D in `find . -type d`
do
    //Do whatever you need with D
done

你可以试试:

#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/

for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
  cd "$f"
  <your job here>
done

或类似的…

解释:

找到。-maxdepth 1 -mindepth 1 type d: 只查找最大递归深度为1(仅为$1的子目录)和最小递归深度为1(不包括当前文件夹)的目录。