Akshay Yeluru
Akshay Yeluru

Reputation: 31

Can I check Ngnix running status and return 1 or 0 based on the state?

I have a command which checks whether a port is open and returns zero or one.

netstat -ano | grep ':443\s' | if grep -q LISTEN; then echo 0; else echo 1; fi

I would like to know how can we write a command to check whether nginx is running and return 1 or 0?

Upvotes: 1

Views: 815

Answers (4)

rbrtflr
rbrtflr

Reputation: 11

With systemd you can use "systemctl status nginx" and then look at the "$?" variable (exit code of the last executed command).

I think something like this will do the job:

systemctl status nginx >/dev/null 2>&1; if [ $? -gt 0 ]; then echo 0; else echo 1; fi

Upvotes: 0

Bsquare ℬℬ
Bsquare ℬℬ

Reputation: 4487

You can use the pidof tool which comes with system package (for instance procps-ng under RedHat GNU/Linux distributions), redirect the output you do not want, and manage to gave the status you want.

For sustainability, I wrote you this tiny script you can integrate in yours:

#!/bin/bash

function isRunning() {
  local _processName="$1"
  pidof "$_processName" >/dev/null
}

isRunning nginx && echo "It is running" || echo "Not running"

If you really want to echo a 1 or 0, you can, but it would generally be useless.

Instead you can act according to the return of this function isRunning.

Edit according to your comment: you can use this for any process:

#!/bin/bash

function isRunning() {
  local _processName="$1"
  echo -ne "Checking if $_processName is running ... " 
  pidof "$_processName" >/dev/null && echo "1" || echo "0"
}

isRunning nginx
isRunning java
isRunning httpd

You can remove the echo in the function if you do not want anything else than 0/1.

Upvotes: 1

Matias Barrios
Matias Barrios

Reputation: 5054

The best way is actually use systemd since Nginx runs as a service. you can even interpret the status of running function later on according to systemd exit codes.

function running() { 
   [[ ! -z $1 ]] &&   systemctl status $1 2>&1 >/dev/null  || return 255; 
   return $?; 
}

running nginx && echo "Its running" || echo "Its not"

Upvotes: -1

Ipor Sircer
Ipor Sircer

Reputation: 3141

pidof nginx && echo 1 || echo 0

Upvotes: 2

Related Questions