Reputation: 483
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.
Upvotes: 7
Views: 38984
Reputation: 66243
Instead of
if [ "$pid"="" ]
please try
if [ "$pid" = "" ]
The whitespace is around =
is important.
You can also try
if [ -z "$pid" ]
Upvotes: 15
Reputation: 7516
Instead of the nebulous matching provided by:
pid=`ps -ef | grep "mylittleprogram" | grep -v grep | awk ' {print $2}'`
...and the archaic backtick syntax, consider this which matches the process basename exactly and produces an output format of your choice (here, the process pid if it exists):
pid=$(ps -C mylittleprogram -opid=)
Then, as noted, simply test for an empty value:
[ -z "${pid" ] && echo "no process" || echo "I live as $pid"
The equal sign following the output element name suppresses the heading that you would normally get. Manpages are your friend.
Upvotes: 0
Reputation: 392911
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
Upvotes: 3