Skip to content

Instantly share code, notes, and snippets.

@liladas liladas/systemd.sh
Last active Apr 12, 2018

Embed
What would you like to do?
Helper script for installing/uninstalling systemd service files
#!/bin/bash
CMD="$(basename $0)"
usage() {
echo "usage: $CMD [-f file | -n name ] [ -i | -u | -s | -r ] [-v] | [-h]"
echo ''
echo 'systemd service installer'
echo 'optional arguments:
-h, --help show this help message and exit
-f, --file service definition file (systemd unit)
-n, --name service name (can be used with uninstall and status options)
-i, --install install service
-u, --uninstall uninstall service
-r, --restart restart service
-s, --status check status
--status
-v, --verbose print verbose output'
exit 1
}
#!/bin/sh
if [ ! $# -gt 0 ] ; then
usage
fi
verbose=
install=
uninstall=
status=
restart=
SERVICE_DEFINITION=
NAME=
while [ "$1" != "" ]; do
case $1 in
-f | --file ) shift
SERVICE_DEFINITION=$1
;;
-n | --name ) shift
SERVICE_NAME=$1
;;
-v | --verbose ) verbose=1
;;
-i | --install ) install=1
;;
-u | --uninstall ) uninstall=1
;;
-r | --restart ) restart=1
;;
-s | --status ) status=1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done
if [[ -z $uninstall && -z $install && -z $status && -z $restart ]]
then
echo "No action specified. Please include -i (--install), -u (--uninstall), -s (--status)"
echo ""
usage
fi
if [[ ! -z $install && -z $SERVICE_DEFINITION ]]
then
echo "Please include SERVICE_DEFINITION file with -f (--file) option to install service"
echo ""
usage
fi
# Remove "<extra_identifier>": <service_name><extra_identifier>.service -> <service_name>.service
if [[ ! -z $SERVICE_DEFINITION ]]
then
SERVICE_FILE="$(basename $SERVICE_DEFINITION)"
DIRNAME="$(dirname $SERVICE_DEFINITION)"
SERVICE_NAME="$(echo $SERVICE_FILE | /bin/sed 's/\.[A-Za-z0-9]*\.service//')"
fi
#Attempt to stop/disable service before installing new
if [[ ! -z $uninstall || ! -z $install ]]
then
if [[ -z $SERVICE_NAME ]]
then
echo "Missing SERVICE_NAME. Please include file or name of service to uninstall with -f (--file) or -n (--name) options."
echo ""
usage
fi
set -x
service $SERVICE_NAME stop
systemctl disable $SERVICE_NAME
rm -f /etc/systemd/system/$SERVICE_NAME.service
{ set +x; } 2>/dev/null
fi
if [[ ! -z $install ]]
then
set -x
# Copy service definition file to systemd dir
cp $SERVICE_DEFINITION /etc/systemd/system/$SERVICE_NAME.service
# reload services to pick up changes
systemctl daemon-reload
# enable new service
systemctl enable $SERVICE_NAME --now
{ set +x; } 2>/dev/null
fi
if [[ ! -z $restart && ! -z $SERVICE_NAME ]]
then
echo "Restarting service:"
set -x
service $SERVICE_NAME restart
{ set +x; } 2>/dev/null
fi
if [[ ! -z $status || ! -z $install ]]
then
echo "Service Status:"
set -x
service $SERVICE_NAME status
{ set +x; } 2>/dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.