BASH

Check if a Port is in Use or a Service is Running

Write a Bash script to verify if a specific TCP port is actively being used by a process or if a given service process is currently running on the system.

#!/bin/bash

# Configuration
CHECK_PORT=80 # Port number to check
CHECK_SERVICE_KEYWORD="nginx" # Keyword to search in process list (e.g., "apache2", "node", "php-fpm")

# --- Functions ---
log_message() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

check_port_status() {
    PORT=$1
    # Using ss (socket statistics) is more modern and often faster than netstat
    # -t: TCP, -l: listening, -n: numeric ports, -p: show process
    if ss -tlnp | grep -q ":$PORT\b"; then
        log_message "Port $PORT is OPEN and listening."
        ss -tlnp | grep ":$PORT\b"
        return 0 # Port is in use
    else
        log_message "Port $PORT is CLOSED or not listening."
        return 1 # Port is not in use
    fi
}

check_service_status() {
    KEYWORD=$1
    # pgrep finds processes by name or other attributes
    if pgrep -f "$KEYWORD" > /dev/null; then
        log_message "Service/Process matching '$KEYWORD' is RUNNING."
        pgrep -fla "$KEYWORD" # Show full details
        return 0 # Service is running
    else
        log_message "Service/Process matching '$KEYWORD' is NOT running."
        return 1 # Service is not running
    fi
}

# --- Main Script ---
log_message "Starting system checks..."

log_message "
--- Checking Port $CHECK_PORT ---"
check_port_status "$CHECK_PORT"
PORT_STATUS=$?

log_message "
--- Checking Service '$CHECK_SERVICE_KEYWORD' ---"
check_service_status "$CHECK_SERVICE_KEYWORD"
SERVICE_STATUS=$?

log_message "
--- Summary ---"
if [ $PORT_STATUS -eq 0 ]; then
    log_message "Port $CHECK_PORT: IN USE"
else
    log_message "Port $CHECK_PORT: NOT IN USE"
fi

if [ $SERVICE_STATUS -eq 0 ]; then
    log_message "Service '$CHECK_SERVICE_KEYWORD': RUNNING"
else
    log_message "Service '$CHECK_SERVICE_KEYWORD': NOT RUNNING"
fi

log_message "Finished system checks."
How it works: This script provides two functions: one to check if a specific TCP port is currently being listened on by a process, and another to verify if a process matching a given keyword (like a service name) is running. It uses `ss` for port checks and `pgrep` for process checks, which are efficient tools for system diagnostics and health monitoring of web servers or services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs