Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display last command that failed when using bash set -e?

Tags:

bash

I am using set -e to stop execution of a script on first error.

The problem is that this does not tell me what went wrong.

How can update a bash script so it will display me the last command that failed?

like image 382
sorin Avatar asked May 24 '12 18:05

sorin


People also ask

How do I know if bash command failed?

Now, every command run in bash shell returns a value that's stored in the bash variable “$?”. To get the value, run this command. $ echo $? If a command succeeded successfully, the return value will be 0.

How do you exit a script if command fails?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.


2 Answers

Instead of set -e, use an ERR trap; you can pass $BASH_LINENO in to get the specific line number on which the error occurred. I provide a script taking advantage of this in my answer at https://stackoverflow.com/a/185900/14122

To summarize:

error() {
   local sourcefile=$1
   local lineno=$2
   # ...logic for reporting an error at line $lineno
   #    of file $sourcefile goes here...
}
trap 'error "${BASH_SOURCE}" "${LINENO}"' ERR
like image 110
Charles Duffy Avatar answered Oct 03 '22 13:10

Charles Duffy


  1. make err.sh

    set -e
    trap 'echo "ERROR: $BASH_SOURCE:$LINENO $BASH_COMMAND" >&2' ERR
    
  2. include it (. err.sh) in all your scripts.

  3. replace any

    ... | while read X ; do ... ; done

    with

    while read X ; do ... ; done < <( ... )

    in your scripts for the trap to give the correct line number/command in the error message

like image 21
user1133275 Avatar answered Oct 03 '22 12:10

user1133275