This script's only responsibility is to keep a process alive. Forever.
It's sole dependencies shall be bash
and coreutils
. I'm not sure if it would be compatible with sh
, that would be even better.
#!/bin/bash
#
# (c) Netcetera AG
# Author: Christian Mäder
date="10.07.2015"
version="1.0"
#
respawn() {
while true; do
$myprocess
exit_code=$?
now=`date +"%Y-%m-%dT%H:%M:%S%z"`
if [ $exit_code -ne 0 ] || [ $force -eq 1 ]; then
if [ $quite -eq 0 ]; then
echo "$now | service $myprocess crashed with code $?. Restarting after ${timeout}s." >&2
fi
sleep $timeout
else
break
fi
done
}
help() {
echo "Usage: $1 [-f] [-q] [-t #] \"command\""
echo " $1 -v"
echo " $1 -h"
echo
echo " -v : Shows the version of this tool."
echo " -h : Shows this help text."
echo " -f : Restart the program even if it exited with an exit"
echo " status of 0."
echo " -q : If set, this script won't write anything to stdout or stderr."
echo " -t # : Seconds for how long the script should wait until"
echo " the restart happend."
echo " command : The command to execute continuously until it exits"
echo " gracefully or forever if -f is set."
echo
echo "Example: $1 -f -t 2 \"echo hello, see you again in two.\""
}
about() {
echo "Respawns a process which dies. Hence it keeps it runnig forever."
echo "Version $version from $date."
}
while true; do
case "$1" in
"--help")
help $0
break
;;
"-h")
help $0
break
;;
"-v")
about
break
;;
"-q")
quite=1
shift
;;
"-f")
force=1
shift
;;
"-t")
if [[ $2 =~ '^[0-9]+$' ]]; then
timeout=$2
shift
fi
shift
;;
*)
if [ $# -eq 0 ]; then
about
echo
help $0
else
quite=${quite-0}
force=${force-0}
timeout=${timeout-"1"}
myprocess=$1
respawn
fi
break
;;
esac
done
For everyone's reference have I created a gist with an updated version which incorporated the feedback.
init
orupstart
orgod
etc.. \$\endgroup\$#!/bin/bash
to#!/bin/sh
. \$\endgroup\$now=`date +"%Y-%m-%dT%H:%M:%S%z"`
tonow=$(date +"%Y-%m-%dT%H:%M:%S%z")
\$\endgroup\$