Last active
November 19, 2015 12:32
-
-
Save cimnine/68c91efbbca8a6fd7397 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# (c) Netcetera AG | |
date="19.11.2015" | |
version="1.2" | |
# | |
help() { | |
script=$(basename "$1") | |
echo "Usage: $script [-f] [-q] [-t #] \"command\"" | |
echo " $script -v" | |
echo " $script -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 running forever." | |
echo "Version $version from $date." | |
} | |
respawn() { | |
command="$@" | |
while :; do | |
$command | |
exit_code=$? | |
if [ $exit_code -eq 0 ] && [ "$force" -ne 1 ]; then | |
break | |
elif [ "$quiet" -eq 0 ]; then | |
echo "$(date +\"%Y-%m-%dT%H:%M:%S%z\") | service $command crashed with code $?. Restarting after ${timeout}s." >&2 | |
fi | |
sleep "$timeout" | |
done | |
} | |
while true; do | |
case "$1" in | |
"--help"|"-h") | |
help "$0" | |
break | |
;; | |
"-v") | |
about | |
break | |
;; | |
"-q") | |
quiet=1 | |
shift | |
;; | |
"-f") | |
force=1 | |
shift | |
;; | |
"-t") | |
case "$2" in | |
[0-9]*) | |
timeout=$2 | |
shift | |
;; | |
*) | |
echo "The parameter for -t must be a positive number, but was '$2'." | |
help "$0" | |
break | |
;; | |
esac | |
shift | |
;; | |
*) | |
if [ $# -eq 0 ]; then | |
about | |
echo | |
help "$0" | |
else | |
quiet=${quiet-0} | |
force=${force-0} | |
timeout=${timeout-"1"} | |
respawn "$@" | |
fi | |
break | |
;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment