Bash ERR, RETURN, EXIT traps passing the syserr text

Is there a means of passing the syserr text for the last command to a bash error, return or exit trap? If there is not a means to do this should there be a means to do this? The syserr messages I am seeking are those generated by the system and not by me. I can create a mechanism to pass my own messages to the trap function. What I would like is a method to get those NOT generated by my code.

Many of the error codes have numerous reasons (especially 1) meaning the syserr text is required to be able to consider the actual meaning of the error.

    local l_command=$1        #  $BASH_COMMAND
    local l_lineno=$2         #  $LINENO
    local l_rc=$3             #  $?
    local l_msg=$4            #  {what?}


trap 'trapERR "$BASH_COMMAND" "$LINENO" "$?" "{what?}"' ERR

Hi Pasha-19,

Welcome to our forums.

If I get your question right, you can capture the last command’s error messages by redirecting stderr (standard error) output anywhere you like. Namely, my example below will redirect the error message (trying to use cd to a non-existent directory) to file, and then process it:



cd none 2> "$ERR_TXT"

echo "the error message of the change directory command is: $(cat "$ERR_TXT")"

Running this would result in the following (assuming there really isn’t a “none” subdirectory where I run the script:

$ ./ 
the error message of the change directory command is: ./ line 5: cd: none: No such file or directory