2

I have created the following simple backup script for my Ubuntu machine:

#!/bin/bash

set -e

echo "Mounting network share" sudo mkdir -p /var/backup sudo mount -t nfs 192.168.178.33:/volume1/backup_data /var/backup

echo "Creating backups" rsync -av /volume1/ /var/backup --delete

echo "Unounting network share" sudo umount /var/backup

set +e

This is executed via a cronjob every night and works quite well.

Now I would like to add some reporting (e.g. via Gotify). A success/failure notification would be very helpful. This is how I can send a Gotify notification:

curl "http://192.168.178.30:8080/message?token=XXXXXXXX" -F "title=my title" -F "message=my message"

What would be the best way to integrate this into the script? Is there some kind of global success/failure flag one could query?

Boris
  • 121

1 Answers1

5

Is there some kind of global success/failure flag one could query?

No, but you can use trap to trigger the execution of a command / a function as soon as a command returns a non-zero status.

The way I'd go about this would be: I'd remove set -e and trap all errors (since we're at it reporting the command that errored out and the command's exit status), exiting the script with the same exit status of the command that errored out (or with a custom exit status, depending on the context in which the script is run):

#!/usr/bin/env bash

function handle_error() { ret=$? printf "Error while running '%s'; command exited with exit status '%d'\n" "${BASH_COMMAND}" "${ret}" exit $ret }

trap handle_error ERR

echo 'This will be executed' (exit 255) echo 'This will not be executed'

% ./script1.sh   
This will be executed
Error while running '( exit 255 )'; command exited with exit status '255'
# the script exits with exit status 255

Applying this to your script:

#!/bin/bash

function handle_error() { ret=$? curl "http://192.168.178.30:8080/message?token=XXXXXXXX" -F "title=Error while running '${BASH_COMMAND}'" -F "message=Command exited with exit status '${ret}'" exit $ret }

trap handle_error ERR

echo "Mounting network share" sudo mkdir -p /var/backup sudo mount -t nfs 192.168.178.33:/volume1/backup_data /var/backup

echo "Creating backups" rsync -av /volume1/ /var/backup --delete

echo "Unounting network share" sudo umount /var/backup

kos
  • 41,268