Skip to content

Files

Latest commit

 

History

History
48 lines (32 loc) · 1.32 KB

SC2164.md

File metadata and controls

48 lines (32 loc) · 1.32 KB

Pattern: Missing fault handling for cd

Issue: -

Description

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 directory. This can be messy, especially if the operations involve creating or deleting a lot of files.

To avoid this, make sure you handle the cases when cd fails. Ways to do this include

  • cd foo || exit as suggested to just abort immediately
  • if cd foo; then echo "Ok"; else echo "Fail"; fi for custom handling
  • <(cd foo && cmd) as an alternative to <(cd foo || exit; cmd) in <(..), $(..) or ( )

Example of incorrect code:

cd generated_files
rm -r *.c

func(){
  cd foo
  do_something
}

Example of correct code:

cd generated_files || exit
rm -r *.c

# For functions, you may want to use return:
func(){
  cd foo || return
  do_something
}

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.

Further Reading