BASH

Bash Script to Manage Nginx Service

Create a flexible Bash script to easily start, stop, restart, reload configurations, or check the status of your Nginx web server service using systemctl.

#!/bin/bash

# --- Configuration ---
SERVICE="nginx" # Name of the service to manage
# ---------------------

# Check if systemctl is available
if ! command -v systemctl &> /dev/null; then
    echo "Error: systemctl command not found. This script requires systemd." >&2
    exit 1
fi

case "$1" in
    start)
        echo "Starting $SERVICE..."
        sudo systemctl start "$SERVICE"
        if [ $? -eq 0 ]; then echo "$SERVICE started successfully."; else echo "Failed to start $SERVICE." >&2; fi
        ;;
    stop)
        echo "Stopping $SERVICE..."
        sudo systemctl stop "$SERVICE"
        if [ $? -eq 0 ]; then echo "$SERVICE stopped successfully."; else echo "Failed to stop $SERVICE." >&2; fi
        ;;
    restart)
        echo "Restarting $SERVICE..."
        sudo systemctl restart "$SERVICE"
        if [ $? -eq 0 ]; then echo "$SERVICE restarted successfully."; else echo "Failed to restart $SERVICE." >&2; fi
        ;;
    status)
        echo "Checking $SERVICE status..."
        sudo systemctl status "$SERVICE"
        ;;
    reload)
        echo "Reloading $SERVICE configuration..."
        sudo systemctl reload "$SERVICE"
        if [ $? -eq 0 ]; then echo "$SERVICE configuration reloaded successfully."; else echo "Failed to reload $SERVICE configuration." >&2; fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|reload}" >&2
        exit 1
        ;;
esac

exit 0
How it works: This script provides a convenient command-line interface for managing the Nginx service (or any other `systemd` service). It uses a `case` statement to handle different actions based on the first command-line argument, such as `start`, `stop`, `restart`, `status`, or `reload`. It leverages `systemctl`, the standard service manager on modern Linux distributions, and prepends `sudo` for elevated privileges. The script includes basic error handling to inform the user if the command fails and ensures `systemctl` is available before proceeding. This simplifies common server administration tasks for web developers.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs