Skip to content

Instantly share code, notes, and snippets.

@annahri
Created December 30, 2019 10:00
Show Gist options
  • Save annahri/ce5951e5d6a119ebc74f07f8d7195c81 to your computer and use it in GitHub Desktop.
Save annahri/ce5951e5d6a119ebc74f07f8d7195c81 to your computer and use it in GitHub Desktop.
Teroos.sh -- Runs a bash script for..ever... until stopped
#!/bin/bash
# teroos - Runs a script for..ever... until stopped
set -eo pipefail
USAGE() {
echo "Usage: $0 <start|stop|status|install|uninstall> /path/to/script.sh"
exit
}
[ $# -eq 0 ] && USAGE
# Operations
while [ $# -gt 0 ]; do
case $1 in
start)
ACTION="run"
SCRIPT=$2
shift
shift
;;
stop)
ACTION="stop"
SCRIPT=$2
shift
shift
;;
status)
ACTION="info"
SCRIPT=$2
shift
shift
;;
install)
ACTION="install"
SCRIPT=$2
shift
shift
;;
uninstall)
ACTION="uninstall"
SCRIPT=$2
shift
shift
;;
*)
echo "Operation $1 not found"
USAGE
exit 1
;;
esac
done
TPATH=/tmp/teroos
[ ! -d $TPATH ] && mkdir -p $TPATH
REALPATH=$(realpath $SCRIPT)
BASENAME=$(basename $REALPATH)
PIDFILE=$TPATH/${BASENAME}.pid
case $ACTION in
run)
if [ -f $PIDFILE ]; then
echo "$BASENAME is running for..ever..."
exit 0
else
echo "Running $BASENAME forever..."
while :; do eval bash $REALPATH; wait; done > /dev/null 2>&1 & echo $! > $PIDFILE
fi
;;
stop)
if [ ! -f $PIDFILE ]; then
echo "$BASENAME is not running"
exit 0
fi
echo "Killing $BASENAME with PID $(cat $PIDFILE)..."
kill -SIGTERM $(cat $PIDFILE) && rm $PIDFILE && echo "Done"
;;
info)
if [ -f $PIDFILE ]; then
echo "$BASENAME is running fine (hopefully) with PID $(cat $PIDFILE)"
else
echo "$BASENAME is not running yet. Run it with [start] operator."
fi
;;
install)
# Install script to run as systemd service, so it will run at startup
if [ "$EUID" -ne 0 ]
then echo "Please run as root to install as systemd service"
exit
fi
echo "Installing $BASENAME as systemd service..."
spath=$(realpath $0)
read -p "Creating ${BASENAME}.service, Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
cat << EOF > /etc/systemd/system/${BASENAME}.service
[Unit]
Description= $BASENAME service
[Service]
ExecStart=$spath start $REALPATH
ExecStop=$spath stop $REALPATH
Restart=always
PIDFile=$PIDFILE
[Install]
WantedBy=default.target
EOF
# Strip leading & trailing whitespaces
sed -i 's/^[ \t]*//;s/[ \t]*$//' /etc/systemd/system/${BASENAME}.service
echo "Reloading systemd daemon"
systemctl daemon-reload && echo "Done"
echo "You can now start $BASENAME as service, via systemctl <start|stop|status|...> "
;;
uninstall)
if [ "$EUID" -ne 0 ]
then echo "Please run as root to install as systemd service"
exit
fi
systemctl stop $BASENAME
systemctl disable $BASENAME
rm /etc/systemd/system/${BASENAME}.service
systemctl daemon-reload
systemctl reset-failed
echo "Uninstall ${BASENAME}.service done"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment