diff --git a/SC2164.md b/SC2164.md new file mode 100644 index 0000000..5d9de23 --- /dev/null +++ b/SC2164.md @@ -0,0 +1,25 @@ +## Use cd ... || exit in case cd fails. + +### Problematic code: + + cd generated_files + rm -r *.c + +### Correct code: + + cd generated_files || exit + rm -r *.c + +### Rationale: + +`cd` can fail for a variety of reasons: misspelled paths, missing directories, missing permissions, broken symlinks and more. + +If/when it does, the script will keep going and do all its operations in the wrong direction. This can be messy, especially if the operations involve creating or deleting a lot of files. + +You should therefore always check the condition of `cd`, either with `|| exit` as suggested, or things like `if cd somewhere; then ...; fi`. + +### Exceptions: + +ShellCheck does not give this warning when `cd` is on the left of a `||` or `&&`, or the condition of a `if`, `while` or `until` loop. Having a `set -e` command anywhere in the script will disable this message, even though it won't necessarily prevent the issue. + +If you are accounting for `cd` failures in a way shellcheck doesn't realize, you can disable this message with a [[directive]]. \ No newline at end of file