BASH
Automate Web Server Restart with Status Check
Learn to write a robust bash script for restarting Nginx or Apache, including pre-check for configuration syntax and post-check for service status.
#!/bin/bash
SERVICE_NAME="nginx" # or "apache2"
echo "Attempting to restart $SERVICE_NAME..."
# Check configuration syntax first
if sudo $SERVICE_NAME -t &>/dev/null; then
echo "$SERVICE_NAME configuration syntax is OK."
else
echo "Error: $SERVICE_NAME configuration syntax is invalid. Aborting restart."
sudo $SERVICE_NAME -t
exit 1
fi
# Restart the service
sudo systemctl restart $SERVICE_NAME
# Check if service restarted successfully
if systemctl is-active --quiet $SERVICE_NAME; then
echo "$SERVICE_NAME restarted successfully."
else
echo "Error: Failed to restart $SERVICE_NAME. Check logs for details."
exit 1
fi
How it works: This script safely restarts a web server (Nginx or Apache) by first verifying its configuration syntax. If syntax is valid, it proceeds with a `systemctl restart` command. Finally, it confirms the service is active, providing clear feedback on success or failure, making it robust for deployment or maintenance tasks on Linux systems using systemd.