我正在尝试编写一个脚本,该脚本将在具有许多单级子目录的给定目录中运行。该脚本将 cd 进入每个子目录,对目录中的文件执行命令,然后 cd out 继续到下一个目录。做这个的最好方式是什么?
psu*_*usi 118
for d in ./*/ ; do (cd "$d" && somecommand); done
Run Code Online (Sandbox Code Playgroud)
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)