Skip to content

Instantly share code, notes, and snippets.

@gipert
Created April 29, 2019 15:12
Show Gist options
  • Save gipert/84668f766d48e462f06ad77ef033390b to your computer and use it in GitHub Desktop.
Save gipert/84668f766d48e462f06ad77ef033390b to your computer and use it in GitHub Desktop.
Simple skeleton for auto-daemonizing bash script
#!/bin/bash
#
# simple bash daemon skeleton
#
# Author: Luigi Pertoldi - luigi.pertoldi@hotmail.it
# Created: Mon 29 Apr 2019
usage() {
echo >&2 "USAGE: `basename $0` [OPTIONS]"
echo >&2 ""
echo >&2 " OPTIONS:"
echo >&2 " -v, --verbose : enable verbose mode"
echo >&2 " -r, --refresh <n-sec> : set refresh interval (default 10)"
echo >&2 " -d, --daemon : start indaemon mode"
echo >&2 " -k, --kill : kill all running qwatch daemons"
echo >&2 " -h, --help : display this help message and exit"
exit 1;
}
refresh=10
daemon=false
options='r:u:vhkd'
longoptions='refresh:,daemon,kill,help'
parsed=$(getopt --name `basename $0` --options $options --longoptions $longoptions -- "$@")
[ $? -eq 0 ] || exit 1
eval set -- "$parsed"
while true; do
case "$1" in
-v)
set -xv
shift
;;
-r | --refresh)
refresh=$2
shift 2
;;
-k | --kill)
killall -s TERM qwatch
exit
;;
-d | --daemon)
daemon=true
shift
;;
--)
shift
break
;;
-h | --help | *)
usage
;;
esac
done
# main loop
routine() {
trap "echo 'INFO: quitting gracefully'; exit 1" TERM INT QUIT
trap "echo \"daemon [pid $$] exited unexpectedly.\"; exit 1" SEGV BUS ILL HUP ABRT
while true; do
sleep $refresh
# do your stuff
# ...
done
}
# to daemonize or not to daemonize?
if [ $daemon = true ]; then
routine &
disown
echo "INFO: process started in background with pid $$"
else
echo "INFO: starting routine, use Ctrl+C to kill."
routine
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment