Skip to content

Instantly share code, notes, and snippets.

@RichardBronosky
Created January 18, 2019 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardBronosky/6954739f58a3272551c154d14ef1cd6c to your computer and use it in GitHub Desktop.
Save RichardBronosky/6954739f58a3272551c154d14ef1cd6c to your computer and use it in GitHub Desktop.
watcher.sh runs a comand at an internal and speaks when the status changes.
#!/bin/bash
# TODO:
# This was a 5 minute hack.
# Currently assumes presence of `say` command (macOS). Make more OS tolerant. Possibly changing *_MSG to *_CMD
usage(){
cat<<USAGE
$0 runs a comand at an internal and speaks when the status changes.
Accepts optional ENV vars: SUCCESS_MSG and FAILURE_MSG
Usage:
$0 <interval_seconds> <command>
Example:
SUCCESS_MSG="Internet online" FAILURE_MSG="Internet offline" watcher.sh 4 dig google.com +time=1
USAGE
}
if [[ $# -lt 2 ]]; then
usage
exit 255
fi
success_message="${SUCCESS_MSG:-Command was successful}"
failure_message="${FAILURE_MSG:-Command failed}"
default_message=""
delay=$1
shift
cmd="$@"
tmp1=$(mktemp /tmp/$(basename $0).curr.XXXXX)
tmp2=${tmp1/curr/prev}; touch $tmp2
run_cmd(){
$cmd
status=$?
cp $tmp1 $tmp2
if $(exit $status); then
echo $success_message > $tmp1
else
echo $failure_message > $tmp1
fi
if ! diff $tmp1 $tmp2 > /dev/null; then
say "$(cat $tmp1)"
fi
}
run_conditional(){
true
}
main(){
echo $default_message | tee $tmp1 > $tmp2
while run_conditional; do
run_cmd
sleep $delay
done
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment