Change directory using loop in linux

喜欢而已 提交于 2021-02-10 05:41:15

问题


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

However I am getting error:

 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")

回答1:


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

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

Yet another way is to use pushd and popd:

for i in {1..10}; do
    pushd dir/subdir$i || continue
    cmd1
    cmd2
    popd
done


来源:https://stackoverflow.com/questions/46973632/change-directory-using-loop-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!