Skip to content

Instantly share code, notes, and snippets.

@morxa
Last active April 14, 2021 12:00
Show Gist options
  • Save morxa/5ec60f6e558b15d507209231b10c9720 to your computer and use it in GitHub Desktop.
Save morxa/5ec60f6e558b15d507209231b10c9720 to your computer and use it in GitHub Desktop.
Run a command repeatedly and send a notification when it succeeds.
#! /bin/bash
#
# run_and_notify.bash
# Copyright (C) 2021 Till Hofmann <hofmann@kbsg.rwth-aachen.de>
#
# Distributed under terms of the MIT license.
#
set -e
set -u
set -o pipefail
ARGS=$(getopt --options '+h' --longoptions 'fail-first,help' -- "$@")
eval set -- "$ARGS"
unset ARGS
FAIL_FIRST=false
usage () {
echo "
Usage: $0 [-h] [--help] [--fail-first] <command>
Run a command repeatedly and send a notification when it succeeds.
Example:
\$ $0 ping -c 1 google.com
This will ping google.com until it reaches the host and then send a notification.
This is especially useful when you reboot a host and want to wait until it has rebooted:
\$ ssh target.example.com shutdown -r
\$ $0 --fail-first ping -c 1 target.example.com
optional arguments:
-h, --help show this help message and exit
--fail-first first run the command until it fails, then continue until it succeeds.
"
}
while true; do
case "$1" in
'-h'|'--help')
usage
exit 0
;;
'--fail-first')
FAIL_FIRST=true
shift
continue
;;
'--')
shift
break
;;
*)
echo 'Error parsing arguments!' >&2
exit 1
;;
esac
done
echo "Running $@"
ret=0
$@ || ret=1
echo; echo
if $FAIL_FIRST ; then
echo "Waiting for the command to fail."
echo; echo
while [ $ret -eq 0 ] ; do
sleep 1
ret=0
$@ || ret=1
done
fi
echo "Waiting for the command to succeed."
echo; echo
while [ $ret -ne 0 ] ; do
sleep 1
ret=0
$@ || ret=1
done
notify-send "Command succeeded" "$*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment