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?
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.
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.
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
make err.sh
set -e
trap 'echo "ERROR: $BASH_SOURCE:$LINENO $BASH_COMMAND" >&2' ERR
include it (. err.sh
) in all your scripts.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With