0
0
Bash Scriptingscripting~5 mins

Service health check script in Bash Scripting

Choose your learning style9 modes available
Introduction
A service health check script helps you quickly see if a service on your computer or server is running well or needs attention.
You want to know if your website server is working before telling users.
You need to check if a background job is running without logging into the server.
You want to automate alerts if a service stops unexpectedly.
You are managing multiple servers and want a quick status report.
You want to restart a service automatically if it is not running.
Syntax
Bash Scripting
#!/bin/bash

if systemctl is-active --quiet SERVICE_NAME; then
  echo "SERVICE_NAME is running"
else
  echo "SERVICE_NAME is NOT running"
fi
Replace SERVICE_NAME with the actual name of the service you want to check.
The script uses systemctl, which works on systems with systemd (common in modern Linux).
Examples
Checks if the Apache web server is running and prints the status.
Bash Scripting
#!/bin/bash

if systemctl is-active --quiet apache2; then
  echo "Apache is running"
else
  echo "Apache is NOT running"
fi
Checks if the SSH service is running to allow remote connections.
Bash Scripting
#!/bin/bash

if systemctl is-active --quiet sshd; then
  echo "SSH service is running"
else
  echo "SSH service is NOT running"
fi
Sample Program
This script checks if the cron service is running and prints the result. Cron runs scheduled tasks on Linux.
Bash Scripting
#!/bin/bash

SERVICE_NAME="cron"

if systemctl is-active --quiet "$SERVICE_NAME"; then
  echo "$SERVICE_NAME is running"
else
  echo "$SERVICE_NAME is NOT running"
fi
OutputSuccess
Important Notes
Make sure to run the script with enough permissions to check the service status.
You can replace systemctl with service command on older Linux systems, but syntax differs.
Use quotes around variables to avoid errors if service names have spaces (rare but safe).
Summary
A service health check script tells you if a service is running or stopped.
It uses simple commands like systemctl to check service status.
You can customize it for any service by changing the service name.