Skip to content

Instantly share code, notes, and snippets.

@egdoc
Last active November 13, 2019 09:10
Show Gist options
  • Select an option

  • Save egdoc/754b80ad522cbe9992d44713fe52a6c2 to your computer and use it in GitHub Desktop.

Select an option

Save egdoc/754b80ad522cbe9992d44713fe52a6c2 to your computer and use it in GitHub Desktop.
Inheritance of ERR traps
#!/bin/bash
# The -e or --errexit shell option causes the shell to exit immediately when
# a command returns a non-zero status (with some exceptions). An ERR trap gets
# executed before the shell exits
set -o errexit
trap 'echo trapped!' ERR
# This command will have a non-zero exit status, since a standard user has no
# permission to enter the /root directory. Because of the error the trap will
# be executed.
ls /root
# This code will never be executed, because we set errexit
echo "After the error!"
# Output:
# cannot open directory '/root': Permission denied
# trapped!
#!/bin/bash
# To make ERR traps be inherited in the case of command substitutions,
# functions or subshells we must set the 'errtrace' shell option
set -o errexit
set -o errtrace
trap 'echo trapped!' ERR
# Since we set the errtrace option, this time the trap will be inherited by
# the function and will be trigged on error
myfunc() {
ls /root
}
myfunc
# Output:
# ls: cannot open directory '/root': Permission denied
# trapped!
#!/bin/bash
# An ERR trap is not inherited in the case of command substitutions, functions and
# commands executed in subshells.
set -o errexit
trap 'echo trapped!' ERR
# Because of errexit the shell will immediately exit inside this function,
# and since the the ERR trap it's not inherited, the 'trapped!' message will
# not be printed
myfunc() {
ls /root
}
myfunc
# Output:
# ls: cannot open directory '/root': Permission denied
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment