Inline if shell script

London picture London · Feb 13, 2011 · Viewed 91.2k times · Source

Is it possible to execute shell script in command line like this :

counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ] then; echo "true";
>

Above example is not working I get only > character not the result I'm trying to get, that is "true"

When I execute ps -ef | grep -c "myApplication I get 1 output. Is it possible to create result from single line in a script ? thank you

Answer

Shawn Chin picture Shawn Chin · Feb 13, 2011

It doesn't work because you missed out fi to end your if statement.

counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi

You can shorten it further using:

if [ $(ps -ef | grep -c "myApplication") -eq 1 ]; then echo "true"; fi

Also, do take note the issue of ps -ef | grep ... matching itself as mentioned in @DigitalRoss' answer.

update

In fact, you can do one better by using pgrep:

if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi