3 ms·
Suggestion: You use "set -e". The problem with this is that it's silent about which line the script died at, so if your script doesn't print a lot, you may hav
by waterhouse 8y ago
Suggestion: You use "set -e". The problem with this is that it's silent about which line the script died at, so if your script doesn't print a lot, you may have to do detective work. This is an automatic way of giving you a bit of a hint:
$ cat meh.bash
#!/bin/bash
set -e
die() {
echo "Failed at line $1: $2"
}
trap 'die $LINENO "$BASH_COMMAND"' ERR
echo a
test 1 = 3
echo b
$ ./meh.bash
a
Failed at line 8: test 1 = 3
Adapted from: https://unix.stackexchange.com/a/462157 https://unix.stackexchange.com/a/462157
- shakna 8y agoIf you also set 'x' then you'll get a log of how it's interpreting each line.
- jmcnulty 8y agoThat's useful. Thanks.
- arendtio 8y agoIf your script dies because of `set -e` the detective work is just the punishment to condition yourself to write more stable code in the future ;-) By the way, if you are just using Bash (instead of POSIX /bin/sh) you can do even better. Some time ago I found a stacktrace function somewhere: set -Eeuo pipefail trap stacktrace EXIT function stacktrace { if [ $? != 0 ]; then echo -e "\nThe command '$BASH_COMMAND' triggerd a stacktrace:" for i in $(seq 1 $((${#FUNCNAME[@]} - 2))); do j=$(($i+1)); echo -e "\t${BASH_SOURCE[$i]}: ${FUNCNAME[$i]}() called in ${BASH_SOURCE[$j]}:${BASH_LINENO[$i]}"; done fi }