From bdb9ee05e74d0f5fd45892953e936a4992c1fa28 Mon Sep 17 00:00:00 2001 From: Jeroen De Meerleer Date: Fri, 26 May 2023 14:33:11 +0200 Subject: [PATCH] Add check-systemctl-service.sh script to check if a systemd unit is active. This commit adds the check-systemctl-service.sh script which can be used to check if a systemd unit is active. The script takes in a unit file as an argument and has an optional flag to check for running within the current user. It returns exit codes based on whether the service is active, inactive or unknown. --- check-systemctl-service.sh | 93 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 check-systemctl-service.sh diff --git a/check-systemctl-service.sh b/check-systemctl-service.sh new file mode 100644 index 0000000..21da0eb --- /dev/null +++ b/check-systemctl-service.sh @@ -0,0 +1,93 @@ +#!/bin/bash + +# +#/ +#/ Usage: +#/ check-systemctl-service.sh +#/ +#/ Options: +#/ -u, --user Check for running within current user +#/ +#/ 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=u + LONGOPTS=user + + # -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 + ;; + --) + 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" +GetOptions "$@" + +if [[ $(systemctl ${user} list-unit-files "${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