Operations 3 min read

Bash Script for Managing Nginx Service (start, stop, reload, status)

This article presents a Bash script that uses a case statement to define functions for starting, stopping, reloading, and checking the status of Nginx, explaining each command and providing the full script for practical service management.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Bash Script for Managing Nginx Service (start, stop, reload, status)

The article introduces a Bash script for managing the Nginx web server, illustrating how to use a case statement where each pattern ends with a right parenthesis and commands are executed until a double semicolon ( ;; ), similar to a break in other languages.

It first explains the case syntax, noting that the value after case must be a keyword such as in , and that if no pattern matches, the wildcard * can be used to handle the default case.

The script defines several helper functions:

#!bin/bash
source /etc/init.d/functions
act=$1
te(){
  if [ $? -eq 0 ]; then
    action "Nginx Is $act" /bin/true
  else
    action "Nginx Is $act" /bin/false
  fi
}

start(){
  /usr/sbin/nginx &>/dev/null
  te
}

stop(){
  /usr/sbin/nginx -s stop &>/dev/null
  te
}

reload(){
  /usr/sbin/nginx -s reload
  te
}

status(){
  Ngx_status=$(ps aux|grep "[n]ginx"|egrep -v "vi|sh"|grep master|awk '{print $2}')
  Nginx_Status_Port=$(netstat -lntp|grep nginx|awk '{print $4}')
  echo "Nginx_status_Pid: $Ngx_status"
  echo "Nginx_status_Port: $Nginx_Status_Port"
}

case $1 in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    sleep 1
    start
    ;;
  reload)
    reload
    ;;
  status)
    status
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|reload|}"
    ;;
esac

By invoking the script with arguments such as start , stop , restart , reload , or status , users can control the Nginx service directly from the command line, with the helper function te reporting success or failure.

operationsNginxbashservice managementshell script
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.