You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Joachim Ansorg edited this page Nov 12, 2021
·
6 revisions
Use a ( subshell ) to avoid having to cd back.
Problematic code:
fordirin*/
docd"$dir"
convert index.png index.jpg
cd ..
done
Correct code:
fordirin*/
do
(
cd"$dir"||exit
convert index.png index.jpg
)
done
or
fordirin*/
docd"$dir"||exit
convert index.png index.jpg
cd ..
done
Rationale:
When doing cd dir; somestuff; cd .., cd dir can fail when permissions are lacking, if the dir was deleted, or if dir is actually a file.
In this case, somestuff will run in the wrong directory and cd .. will take you to an even more wrong directory. In a loop, this will likely cause the next cd to fail as well, propagating this error and running these commands far away from the intended directories.
Check cds exit status and/or use subshells to limit the effects of cd.
Exceptions
If you set variables you can't use a subshell. In that case, you should definitely check the exit status of cd, which will also silence this suggestion.