What is the danger of `cd dir` without checking, and how do you fix it?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
If cd fails, the script continues in the wrong directory, and the next command operates on the wrong files:
cd /srv/app/releases/old
rm -rf ./* # if cd failed, this deletes files in the current directory
cd /srv/app/releases/old || exit 1
# or avoid cd entirely
rm -rf -- /srv/app/releases/old
# or isolate it
( cd /srv/app && tar -czf /tmp/app.tgz . )
ShellCheck reports SC2164 for unchecked cd.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner