Last active
November 13, 2019 09:10
-
-
Save egdoc/754b80ad522cbe9992d44713fe52a6c2 to your computer and use it in GitHub Desktop.
Inheritance of ERR traps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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