Shell Configuration
Bash can be configured by passing arguments to the shell invocation, or using the set builtin. Since this has quite an impact on how the script must be written to work, setting up the shell in the script ensures a predictable environment.
See the GNU Manual on Bash Features for more detailed info.
Traps
Use the trap statement to handle signals in a script. This is useful e.g. for handling unexpected errors in commands:
$ bash $ false $ trap 'echo "Error on line ${LINENO}: exited with status ${?}" >&2' ERR $ false Error on line 3: exited with status 1
This can be combined with the shell option errexit to provide an error message before exiting the shell when an unexpected error occurs.
See Bash Guide for Beginners for more information about traps.
Using the set Builtin
The set builtin enables and disables bash options:
set -o option-name # enables the option set +o option-name # disables the option
The nounset option ( bash -u)
With this option enabled, the shell will write an error to stderr and exit if an unset variable is referenced.
If the option is disabled, an unset variable just has the value "":
$ set -o nounset $ echo "x${notSet}x" bash: notSet: unbound variable $ echo $? 1 $ set +o nounset $ echo "x${notSet}x" xx $ echo $? 0
Notice that the shell exits with status 1 when an unset variable is referenced.
The errexit option ( bash -e)
Exit the shell if a command returns a non-zero status (this option is not recommended for interactive shells...). This only applies if the error is not handled, so the test in an if-statement or part of a compound condition can still return a non-zero value:
$ set -o errexit $ false <<shell exits with status 1>> $ false || true <<shell does not exit>> $ echo | false <<shell exits with status 1>> $ false | echo <<shell does not exit>> $ if false; then echo OK; fi <<shell does not exit>>
This is useful for making sure that all error conditions are handled explicitly. It could be a big problem if e.g. a script does not notice that changing directory did not work.
If a script really does not care when a command fails, use command_that_fails || true to explicitly ignore the error.