how to trap errors inside the if statement
bash, bash-trap, error-handling, if-statement
Solution
You can't trap ERR for the test in the if
From bash man:
The ERR trap is not executed if the failed command
is part of the command list immediately following a while or
until keyword, part of the test in an if statement, part of a
command executed in a && or || list, or if the command's return
value is being inverted via !
But you could change this
if xsxsxsxs
then ..
to this
xsxsxsxs
if [[ $? -eq 0 ]]
then ..
Problem
Running the following code: ``` #!/bin/bash set -o pipefail set -o errtrace set -o nounset set -o errexit function err_handler () { local error_code="$?" echo "TRAP!" echo "error code: $error_code" exit } trap err_handler ERR echo "wrong command in if statement" if xsxsxsxs then echo "if result is true" else echo "if result is false" fi echo -e "\nwrong command directly" xsxsxsxs exit ``` produces the following output: ``` wrong command in if statement trap.sh: line 21: xsxsxsxs: command not found if result is false wrong command directly trap.sh: line 29: xsxsxsxs: command not found TRAP! error code: 127 ``` How can I trap the 'command not found' error inside the if statement too?