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?
You can't trap ERR for the test in the if
From bash man:
But you could change this
to this