4

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")
janos
  • 120,954
  • 29
  • 226
  • 236
Avinash Kumar
  • 298
  • 3
  • 13
  • https://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script – Héctor Oct 27 '17 at 11:08
  • The first form is OK but you should check to make sure you're getting back to the original directory or that you're doing the cd'ing (and the operation) in a subshell (i.e., `cd dir/subdir$i; bla bla bla; cd ../..` or `(cd dir/$subdir$i; bla bla bla )`) – Petr Skocik Oct 27 '17 at 11:08
  • I am giving `cd //subdir$i` – Avinash Kumar Oct 27 '17 at 11:14
  • Also, i set `i=1` and tried `cd /dir/subdir$i` where `/dir/subdir$i` is a complete directory starting from root. Still facing the same error. – Avinash Kumar Oct 27 '17 at 11:18
  • Thanks mate @PSkocik . Something weird is happening with the paths. I will sort it now. Directly giving the whole path from root isn't working for me. – Avinash Kumar Oct 27 '17 at 11:29

1 Answers1

5

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
janos
  • 120,954
  • 29
  • 226
  • 236
  • Off-topic, therefor already upvoted: I think `cmd1` and `cmd2` should be skipped when the `cd` fails. Perhaps suggest `cd dir/subdir$i && cmd1 && cmd2`. – Walter A Oct 28 '17 at 18:52