Respecting the cd or exit Pattern Suggested by ShellCheck SC2164
Even if you plan to use set -e it feels like a reasonable idea to add this to most cd commands you use in a script.
For example, in your script instead of cd some/path
you’d do cd some/path || exit
.
The idea is that if you make a typo in your path it could lead to files be
deleted in the wrong directory later on in the script when it’s expected you’re
in that path instead of the original path since the cd
command failed.
Using set -e
in your scripts is a great idea and will
protect you against this in most cases without needing to add || exit
but
this feels similar to concepts around security where having layers of
protection is a good idea.
Perhaps you temporarily set +e
to make it easier to script around an expected
error and forget to turn it back on again. When files are potentially being
created or deleted I like the extra peace of mind especially when || exit
is
so easy to do.
ShellCheck also warns you of this with SC2164.
# Demo Video
Timestamps
- 0:16 – The problem with cd’ing into a path in a script
- 0:47 – Using set -e helps but let’s protect ourselves even more
- 1:13 – The or exit pattern helps protect against errors for any command
- 2:05 – ShellCheck will warn of you and it knows about set -e too
- 3:20 – I ran into this when running my aliases file against ShellCheck
Reference Links
Will you be using this pattern in your shell scripts? Let us know!