本文介绍了在linux中使用循环更改目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更改目录以在每个目录中执行任务.代码如下:
I want to change directory to perform a task in each directory. Following is the code:
for i in {1..10}
do
cd dir/subdir$i
bla... bla.. bla..
done
但是我收到错误:
not found [No such file or directory]
我尝试了以下方法,但仍然出现上述错误:
I have tried the following but still getting the same above error:
cd $(echo dir/subdir"$i")
cd $(eval dir/subdir"$i")
推荐答案
问题可能是因为您要更改的所有目录都是相对于原始基目录的.解决此问题的一种方法是使用 (...)
子外壳:
The problem is probably because all the directories you want to change into are relative from the original base directory.One way to solve this is using a (...)
sub-shell:
for i in {1..10}; do
(
cd dir/subdir$i || continue
cmd1
cmd2
)
done
另一种方法是使用cd "$OLDPWD"
返回上一个目录:
Another way is to return to the previous directory using cd "$OLDPWD"
:
for i in {1..10}; do
cd dir/subdir$i || continue
cmd1
cmd2
cd "$OLDPWD"
done
另一种方法是使用 pushd
和 popd
:
Yet another way is to use pushd
and popd
:
for i in {1..10}; do
pushd dir/subdir$i || continue
cmd1
cmd2
popd
done
这篇关于在linux中使用循环更改目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!