From 335c6ef0c74db7bf4de7ac1c234a1dba5045b36e Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Fri, 20 Mar 2020 13:04:22 +0100 Subject: [PATCH] Improve mail wrap script with dynamic args and ignoring a specific exit code --- backup2me.sh | 2 +- mail_wrap_script.sh | 39 +++++++++++++++++++++++++++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/backup2me.sh b/backup2me.sh index ae23c2a..be6c093 100755 --- a/backup2me.sh +++ b/backup2me.sh @@ -12,7 +12,7 @@ function join { if ! lockfile-create -p -r 2 $0; then echo "Another backup is running, aborting" - exit 1 + exit 49 fi ### Program arguments ### diff --git a/mail_wrap_script.sh b/mail_wrap_script.sh index 276115c..0773216 100755 --- a/mail_wrap_script.sh +++ b/mail_wrap_script.sh @@ -1,20 +1,51 @@ #!/bin/bash -SCRIPT=$1 -shift +# Default values +IGNORE_EXIST_CODE=0 +SCRIPT="-1" +# Get arguments +while [ $# -gt 1 ]; do + ARG_NAME=$1 + shift + ARG_VALUE=$1 + shift + + case $ARG_NAME in + --ignore-exit-code) + IGNORE_EXIT_CODE=$ARG_VALUE + ;; + --script) + SCRIPT=$ARG_VALUE + break + ;; + esac +done + +# Exit if bad script +if [ "$SCRIPT" = "-1" ]; then + echo No script specified + echo "Sending error mail" + echo -e "No script specified\n\n\n $(ps $PPID)" | $(dirname $0)/mail.sh "[CRITITCAL] $(hostname) undefined script" + echo "Sent" + exit 1 +fi + +# Create temp logfile FILE_ID=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1) touch /tmp/$FILE_ID.log chmod a-rwx,u+r /tmp/$FILE_ID.log +# Execute script with remaining arguments $SCRIPT "$@" 2>&1 | tee /tmp/$FILE_ID.log ERR=${PIPESTATUS[0]} OUTPUT=$(cat /tmp/$FILE_ID.log) rm /tmp/$FILE_ID.log -if [ $ERR -ne 0 ]; then +# Send mail in case of error +if [ $ERR -ne 0 ] && [ "$ERR" != "$IGNORE_EXIT_CODE" ]; then echo "Sending error mail" - echo -e "An error occured during the execution of $SCRIPT ($ERR).\n\n$OUTPUT" | $(dirname $0)/mail.sh "$(hostname) $SCRIPT failure" + echo -e "An error occured during the execution of $SCRIPT ($ERR).\n\n\n$(ps $PPID)\n\n$OUTPUT" | $(dirname $0)/mail.sh "$(hostname) $SCRIPT failure" echo "Sent" exit 1 fi