Uncover the infinite in IT

Table of Contents
< All Topics

Service Running Status Check and Restart

This script is a simple bash script that checks the status of a service on a Linux system and starts it if it’s not running. It uses the systemctl command, which is a utility for controlling the systemd system and service manager.

Here’s a step-by-step explanation of what the script does:

The script starts by defining a variable service which should be the name of the service you want to check. This is currently set to <service_name>, which is a placeholder. You should replace this with the actual name of the service you want to check, such as nginxssh, or apache2.

The script then checks if the service variable is empty. If it is, the script exits with a usage message.

The script uses the systemctl show -p SubState command to check the current status of the service. The output of this command is stored in the RUNNING variable.

The script then checks if the value of RUNNING is “running”. If it is, the script outputs a message saying that the service is running and then exits.

If the service is not running, the script outputs a message saying that the service is not running and then attempts to start the service using the systemctl start command.

The script then checks the status of the service again. If the service is now running, it outputs a message saying that the service started successfully. If the service did not start successfully, it outputs a message saying that starting the service failed.

Here’s an example of how you might use this script to check the status of the nginx service. Feel free to replace nginx with any service that you want checked on your system.

#!/bin/bash
# Checking the Service Status
service='nginx'
if [ -z "$service" ]; then
echo "usage: $0"
exit 1
fi
echo "Checking $service status"
RUNNING="$(systemctl show -p SubState $service | cut -d'=' -f2)"
if [ "${RUNNING}" = "running" ]; then
echo "$service is Running"
exit 1
else
echo "$service is NOT running"
echo "Starting $service"
START="$(systemctl start $service)"
fi
STATE="$(systemctl show -p SubState $service | cut -d'=' -f2)"
if [ "${STATE}" = "running" ]; then
echo "$service started successfully"
else
echo "Starting failed."
fi

When you run this script, you might see output like this:

Checking nginx status
nginx is NOT running
Starting nginx
nginx started successfully

This indicates that the nginx service was not running when the script was executed, but it was successfully started by the script. If the service was already running, you would see:

Checking nginx status
nginx is Running

This script is a simple way to ensure that a service is running on your system. It could be run periodically, for example from a cron job, to ensure that important services are always up and running.