我正在尝试编写一个脚本,该脚本将在具有许多单级子目录的给定目录中运行。该脚本将 cd 进入每个子目录,对目录中的文件执行命令,然后 cd out 继续进入下一个目录。做这个的最好方式是什么?
答案1
for d in ./*/ ; do (cd "$d" && somecommand); done
答案2
cd
最好的方法是根本不使用:
find some/dir -type f -execdir somecommand {} \;
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.
它不是 POSIX。
答案3
for D in ./*; do
if [ -d "$D" ]; then
cd "$D"
run_something
cd ..
fi
done
答案4
方法一:
for i in `ls -d ./*/`
do
cd "$i"
command
cd ..
done
方法二:
for i in ./*/
do
cd "$i"
command
cd..
done
方法三:
for i in `ls -d ./*/`
do
(cd "$i" && command)
done
我希望这有用。你可以尝试所有的排列和组合。
谢谢:)