![cd 进入所有目录,对该目录中的文件执行命令,然后返回到上一个当前目录](https://linux22.com/image/60062/cd%20%E8%BF%9B%E5%85%A5%E6%89%80%E6%9C%89%E7%9B%AE%E5%BD%95%EF%BC%8C%E5%AF%B9%E8%AF%A5%E7%9B%AE%E5%BD%95%E4%B8%AD%E7%9A%84%E6%96%87%E4%BB%B6%E6%89%A7%E8%A1%8C%E5%91%BD%E4%BB%A4%EF%BC%8C%E7%84%B6%E5%90%8E%E8%BF%94%E5%9B%9E%E5%88%B0%E4%B8%8A%E4%B8%80%E4%B8%AA%E5%BD%93%E5%89%8D%E7%9B%AE%E5%BD%95.png)
我正在尝试编写一个脚本,该脚本将在具有许多单级子目录的给定目录中运行。该脚本将 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
我希望这有用。你可以尝试所有的排列和组合。
谢谢:)