Vampavi
Vampavi

Reputation: 322

Change directory using loop in 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

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

Upvotes: 4

Views: 3547

Answers (1)

janos
janos

Reputation: 124646

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

Upvotes: 5

Related Questions