tags:

views:

239

answers:

4

I wrote a bash-script to check if a process is running. It doesn't work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?

#!/bin/bash
SERVICE=$1

ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
    echo "`date`: $SERVICE service running, everything is fine"
else
    echo "`date`: $SERVICE is not running"
fi

Bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

+1  A: 

Could you just check to see if you get non-empty output from the grep command instead of relying on return values?

Precision
I tried this and have a similar problem. The output is not taken into account. Here the code: #!/bin/bash SERVICE=$1 OUTPUT=$(ps -a | grep -v grep | grep $1) echo $OUTPUT if [ "${#OUTPUT}" -gt 0 ] ; then echo "`date`: $SERVICE service running, everything is fine" else echo "`date`: $SERVICE is not running" fi
elasticsecurity
+1  A: 

Tried your version on BASH version 3.2.29, worked fine. However, you could do something like the above suggested, an example here:

#!/bin/sh

SERVICE="$1"
RESULT=`ps -a | sed -n /${SERVICE}/p`

if [ "${RESULT:-null}" = null ]; then
    echo "not running"
else
    echo "running"
fi
Anders
I tried it out, doesn't work neither. There must be something fishy with my environment (a shared hosting provider).
elasticsecurity
Tried running with #!/bin/sh -x to look at the execution process?
Anders
nothing special: the output is+ SERVICE=rails+ ps -a+ grep -v grep+ grep rails+ result=1+ echo 'exit code: 1'exit code: 1+ '[' 1 -eq 0 ']'++ date+ echo 'Tue May 25 06:52:25 EDT 2010: rails is not running'
elasticsecurity
A: 

I found the problem. ps -ae instead ps -a works.

I guess it has to do with my rights in the shared hosting environment. There's apparently a difference between executing "ps -a" from the command line and executing it from within a bash-script.

elasticsecurity
A: 

Working one.

Made by www.activnet.info

!/bin/bash

CHECK=$0 SERVICE=$1 DATE=date OUTPUT=$(ps aux | grep -v grep | grep -v $CHECK |grep $1) echo $OUTPUT if [ "${#OUTPUT}" -gt 0 ] ; then echo "$DATE: $SERVICE service running, everything is fine" else echo "$DATE: $SERVICE is not running" fi

Dani Radulescu