cd 进入所有目录,对该目录下的文件执行命令,并返回上一个当前目录

Som*_*nes 60 shell-script

我正在尝试编写一个脚本,该脚本将在具有许多单级子目录的给定目录中运行。该脚本将 cd 进入每个子目录,对目录中的文件执行命令,然后 cd out 继续到下一个目录。做这个的最好方式是什么?

psu*_*usi 118

for d in ./*/ ; do (cd "$d" && somecommand); done
Run Code Online (Sandbox Code Playgroud)

  • 因此,由于回答者省略了任何类型的解释,我将尝试一个。`for d in ./*/` 开始一个循环,将 `./*/`(在本例中为文件/文件夹列表)中的每个项目存储在变量 `$d` 中。`do (cd "$d" && somecommand);` 开始循环体。在主体内部,它启动一个 [subshel​​l](http://www.tldp.org/LDP/abs/html/subshel​​ls.html) 并运行 `cd` 和 `somecommand` 命令。由于它是一个子 shell,父 shell(您从中运行此命令的 shell)保留其 CWD 和其他环境变量。`done` 只是关闭循环体。 (18认同)

mur*_*uru 22

最好的方法是根本不使用cd

find some/dir -type f -execdir somecommand {} \;
Run Code Online (Sandbox Code Playgroud)

execdir就像exec,但工作目录不同:

-execdir command {} [;|+]
  Like   -exec,   but  the  specified  command  is  run  from  the
  subdirectory containing the matched file, which is not  normally
  the  directory  in  which  you  started  find.  This a much more
  secure  method  for  invoking  commands,  as  it   avoids   race
  conditions  during resolution of the paths to the matched files.
Run Code Online (Sandbox Code Playgroud)

它不是 POSIX。


小智 7

for D in ./*; do
    if [ -d "$D" ]; then
        cd "$D"
        run_something
        cd ..
    fi
done
Run Code Online (Sandbox Code Playgroud)