Bash allows you to trap signals. Is there a way to actually get the message that printed immediately before (the cause of) a particular signal? It's ERR
in particular I'm interested in. I'm aware that not all signals are associated with a message. Just wondering if bash itself sets a variable or something when it raises an error.
Sample code:
#!/bin/bash
# Running bash 5.0
handler () {
echo "Handling the error"
exit 0
}
trap handler ERR
notacommand
The code above will print:
./example.sh: line 11: notacommand: command not found
Is there a way to see this message inside the handler?
Edit: I know I could save all output to a file and then read the tail of that file when an error occurs. That seems problematic to me, as it's possible that the last message written to the file is something other than the error (especially if any subprocesses are started with &
in the script). I was hoping that maybe bash sets a var or something, in the same way it sets $1
, $?
, $RANDOM
, and others.