Improve mail wrap script with dynamic args and ignoring a specific exit code

This commit is contained in:
Alice Gaudon 2020-03-20 13:04:22 +01:00
parent 0584914cc2
commit 335c6ef0c7
2 changed files with 36 additions and 5 deletions

View File

@ -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 ###

View File

@ -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