From 6087fd6e2f8c9b46a16975ce6bbd62c38abd422b Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 26 Jan 2014 12:43:51 -0800 Subject: [PATCH] Created SC2103 (markdown) --- SC2103.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 SC2103.md diff --git a/SC2103.md b/SC2103.md new file mode 100644 index 0000000..644afdc --- /dev/null +++ b/SC2103.md @@ -0,0 +1,42 @@ +# Consider using ( subshell ), 'cd foo||exit', or pushd/popd instead. + +### Problematic code: + + for dir in */ + do + cd "$dir" + convert index.png index.jpg + cd .. + done + + +### Correct code: + + for dir in */ + do + ( + cd "$dir" || exit + convert index.png index.jpg + ) + done + +or + + for dir in */ + do + cd "$dir" || continue + 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 `cd`s exit status and/or use subshells to limit the effects of `cd`. + +### Contraindications + +None known. \ No newline at end of file