1

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.

vastlysuperiorman
  • 1,694
  • 19
  • 27

1 Answers1

3

Redirect bash's stderr to a file:

#!/bin/bash
# Running bash 5.0

log="error.txt"
exec 2>"$log"

handler () {
 echo "Handling this error: $(< "$log")"
 exit 0
}

trap "handler" ERR
trap "rm $log" EXIT

notacommand

Output:

Handling this error: ./example.sh: line 15: notacommand: command not found
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Thank you for answering, +1. I should have clarified in my question. I was hoping for a method that doesn't involve saving everything to a file and then hoping that the last thing in the file is the message. It seems no such method exists, however. – vastlysuperiorman Nov 02 '20 at 16:14