#!/bin/bash # #/ #/ Usage: #/ check-systemctl-service.sh --help #/ #/ Options: #/ -u, --user Check for running within current user #/ -h, --help Display this help message #/ #/ Checks if a systemd unit is active #/ #/ Exit Codes: #/ 0 Everything OK #/ 2 Unit is not running #/ 3 Unknown status #/ Usage() { grep '^#/' "${script_dir}/${script_name}" | sed 's/^#\/\w*//' } GetOptions() { # https://stackoverflow.com/a/29754866 OPTIONS=uh LONGOPTS=user,help # -use ! and PIPESTATUS to get exit code with errexit set # -temporarily store output to be able to check for errors # -activate quoting/enhanced mode (e.g. by writing out “--options”) # -pass arguments only via -- "$@" to separate them correctly ! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") if [[ ${PIPESTATUS[0]} -ne 0 ]]; then # e.g. return value is 1 # then getopt has complained about wrong arguments to stdout Usage exit 2 fi # read getopt's output this way to handle the quoting right: eval set -- "$PARSED" # now enjoy the options in order and nicely split until we see -- while true; do case "$1" in -u|--user) user='--user' shift 1 ;; -h|--help) Usage exit 0 ;; --) shift break ;; *) echo "SERVICE UNKNOWN - ${1} is not a valid parameter" exit 3 ;; esac done if [ -z ${1+x} ]; then echo "SERVICE UNKNOWN - Unitfile not given" exit 3 else service=${1} fi } user='' service='' LC_NUMERIC="C" script_name=$(basename "${0}") script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) GetOptions "$@" if [[ $(systemctl ${user} list-units "${service}*" | wc -l) -gt 3 ]]; then result=$(systemctl ${user} is-active ${service}) else result='inexistent' fi if [[ $result == 'active' ]]; then rval=0 rmsg="OK" elif [[ $result == 'inexistent' ]]; then rval=1 rmsg="WARNING" else rval=2 rmsg="CRITICAL" fi echo "SERIVCE ${rmsg} - Service $service $result" exit $rval