BASH

Simple Web Service Control Script

Create a basic Bash script to manage a web service, providing convenient start, stop, and status functionalities using `nohup` for background execution.

#!/bin/bash
# A simple script to start, stop, and check the status of a web service.

SERVICE_NAME="MyWebServer"
# Example command to start your web service (e.g., Node.js app, Python Flask app)
# Make sure to adjust this command to your specific service.
START_COMMAND="node server.js"
LOG_FILE="service.log"
PID_FILE="service.pid"

start_service() {
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
        echo "$SERVICE_NAME is already running (PID: $(cat "$PID_FILE"))."
        exit 0
    fi
    echo "Starting $SERVICE_NAME..."
    nohup $START_COMMAND > "$LOG_FILE" 2>&1 & # Run in background, redirect output to log
    echo $! > "$PID_FILE" # Store PID of background process
    echo "$SERVICE_NAME started with PID $!."
}

stop_service() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if kill -0 "$PID" 2>/dev/null; then # Check if process exists
            echo "Stopping $SERVICE_NAME (PID: $PID)..."
            kill "$PID" # Send SIGTERM
            rm -f "$PID_FILE"
            echo "$SERVICE_NAME stopped."
        else
            echo "$SERVICE_NAME is not running, removing stale PID file."
            rm -f "$PID_FILE"
        fi
    else
        echo "$SERVICE_NAME is not running."
    fi
}

status_service() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if kill -0 "$PID" 2>/dev/null; then # Check if process exists
            echo "$SERVICE_NAME is running (PID: $PID)."
        else
            echo "$SERVICE_NAME is not running, stale PID file found."
        fi
    else
        echo "$SERVICE_NAME is not running."
    fi
}

case "$1" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    status)
        status_service
        ;;
    restart)
        stop_service
        start_service
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac
How it works: This Bash script provides a simple interface for managing a web service or any background process. It defines functions for `start`, `stop`, and `status`. The `start_service` function uses `nohup` to run the service command in the background, redirecting its output to a log file and storing its Process ID (PID) in a `PID_FILE`. The `stop_service` function reads the PID from this file and sends a termination signal to the process. The `status_service` function checks if the process is still running. This pattern is useful for local development, simple server deployments, or quick testing without relying on more complex process managers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs