bash: Scripts called with `source` should not use `set`

Running a bash script runs it in a new shell, so it can not change the original shell's pwd. You can source the script in order to run it in the context of the current shell, thereby allowing cd to change the current shell's pwd.

Best practices for writing bash scripts might include setting defensive shell options to make programming slightly safer, for example:

set -o nounset
set -o errexit
set -o pipefail

Unfortunately, if that source is run with source then the script will set those options for the calling shell. That is highly likely to cause issues with that shell.

For example, any part of the shell's prompt could:

So once a carefully written bash script is run with source, the shell is likely to exit immediately as the prompt violates the newly tightened settings. ☹️

Published on: 10 Aug 2024