Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Do Statement with blank/empty grep return?

This is the code for my foobar.sh:

!#/bin/bash
while [ 1 ]
do
    pid=`ps -ef | grep "mylittleprogram" | grep -v grep | awk ' {print $2}'`
    echo $pid
    if [ "$pid"="" ]
    then
            echo "Process has ended lets get this show on the road..."
            exit
    else
            echo "Process has not ended yet"
    fi
    sleep 6
done

I'm basically running a infinate loop which will execute command X once a monitored process has ended but I end up getting the following message as my script loops:

./foobar.sh: line 7: [: missing `]'
Process has not ended yet

Is there a way of making the script accept that zero feed back will trigger my 'Then' statement and execute command X since it is not liking the current method.

like image 701
bikerben Avatar asked Oct 27 '11 21:10

bikerben


3 Answers

Instead of

if [ "$pid"="" ]

please try

if [ "$pid" = "" ]

The whitespace is around = is important.

You can also try

if [ -z "$pid" ]
like image 58
A.H. Avatar answered Nov 15 '22 06:11

A.H.


I'd do

while pgrep -fl "mylittleprogram"; do sleep 6; done
exit # process has ended

(pgrep is in package psmisc IIRC)

I've just tested it. You could redirect the output of pgrep to /dev/null if you wanted the waiting to be silent. Add some more spice to make things uninterruptible:

{
     trap "" INT
     while pgrep -fl "mylittleprogram" >/dev/null
     do 
         sleep 6
     done
     true
} && exit
like image 42
sehe Avatar answered Nov 15 '22 05:11

sehe


The zero test is if [ -z "$pid" ]

like image 41
chx Avatar answered Nov 15 '22 06:11

chx