diff --git a/README.md b/README.md index 38313b3..4f3c268 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,15 @@ When BASHLOG_SYSLOG=1, logs are written to Syslog. This determines the syslog tag to use, defaulting to the name of your script, e.g. `yourscript.sh` +### BASHLOG_EXIT_ON_ERROR + +Default: `0` + +When BASHLOG_EXIT_ON_ERROR=1, `exit 1` will be called after logging an error. + +This will allow your script to exit automatically after logging an error. This feature +is overriden when `DEBUG=1`. + ## Recommended Usage ``` diff --git a/log.sh b/log.sh index ea15a23..98d7176 100755 --- a/log.sh +++ b/log.sh @@ -31,6 +31,7 @@ function log() { local level="${1}"; local upper="$(echo "${level}" | awk '{print toupper($0)}')"; local debug_level="${DEBUG:-0}"; + local exit_on_error="${BASHLOG_EXIT_ON_ERROR:-0}"; shift 1; @@ -120,6 +121,8 @@ function log() { if [ "${debug_level}" -gt 0 ]; then echo -e "Here's a shell to debug with. 'exit 0' to continue. Other exit codes will abort - parent shell will terminate."; bash || exit "${?}"; + elif [ "${exit_on_error}" -gt 0 ]; then + exit 1; fi; ;; *) diff --git a/test.sh b/test.sh index d3c6f21..00b242d 100755 --- a/test.sh +++ b/test.sh @@ -129,10 +129,17 @@ BASHLOG_SYSLOG=1; DEBUG=0; stderr="$(log 'error' "${random_string}" 2>&1 1>/dev/null)"; +exit_code="${?}"; fileout="$(tail -n1 /tmp/${0}.log)"; jsonout="$(tail -n1 /tmp/${0}.log.json)"; syslogout="$(sudo tail -n1 /var/log/syslog)"; +if [ "${exit_code}" -eq 0 ]; then + result ok 'error -> exit code 0'; +else + result fail 'error -> exit code 0'; +fi + grep -q -E $'^\033\[31m[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} \[ERROR\] '"${random_string}"$'\033\[0m$' <<<"${stderr}" \ && result ok 'error -> stderr' \ || result fail 'error -> stderr'; @@ -437,6 +444,26 @@ grep -q -E $'^./log.sh: line [0-9]+: /tmp/'"$(basename ${0})"'.log: Permission d && result ok 'error -> file, Permission denied -> stderr' \ || result fail 'error -> file, Permission denied -> stderr'; +## +# ERROR, EXIT ON ERROR ON +## + +echo "Testing: 'error', BASHLOG_EXIT_ON_ERROR=1"; + +BASHLOG_FILE=0; +BASHLOG_JSON=0; +BASHLOG_SYSLOG=0; +BASHLOG_EXIT_ON_ERROR=1; +DEBUG=0; + +stderr="$(log 'error' "${random_string}" 2>&1 1>/dev/null)"; + +if [ "${?}" -eq 1 ]; then + result ok 'error -> exit code 1'; +else + result fail 'error -> exit code 1'; +fi + ## # INTERACTIVE DEBUG ##