Shell – get different exit status for ps | grep in a script

exit-statusprocesspsshell-script

I am running below script :

#!/bin/bash

ps ax  | grep -q [v]arnish
if [ $? -eq 0 ];then
        echo varnish is running...
        exit 0
else
        echo "Critical : varnish is not running "
        exit 2
fi

The output is like ::

[root@server ~]# sh -x check_varnish_pro.sh
+ ps ax
+ grep -q '[v]arnish'
+ '[' 0 -eq 0 ']'
+ echo varnish is running...
varnish is running...
+ exit 0

When I run same in command line I am getting exit status as 1:

[root@server ~]# ps ax  | grep -q [v]arnish; echo $?
1

The case is like varnish is not installed in the server. This script works fine in a server where varnish is installed.

Why different exit status when run using script and command line? How to improve this script?

Best Answer

When you run a script named check_varnish_pro.sh the test

ps ax  | grep -q [v]arnish

is successful because there is a script named check_varnish_pro running.

Related Question