Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline if shell script

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

like image 238
London Avatar asked Feb 13 '11 18:02

London


People also ask

How do you write if else in bash in one line?

If it is, then echo 1, otherwise echo 0. This is the command that I am using but it only works partially (more info below). Note that I need to write the script in one line. Note: The [s] in some_proces[s] is to prevent grep from returning itself.

What is Z in shell script?

The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh.

How do I check if two strings are equal in Linux?

Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.

How do you check if a variable is defined in bash?

To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined"


2 Answers

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 
like image 151
Shawn Chin Avatar answered Sep 21 '22 19:09

Shawn Chin


Other responses have addressed your syntax error, but I would strongly suggest you change the line to:

 test $(ps -ef | grep -c myApplication) -eq 1 && echo true 

If you are not trying to limit the number of occurrences to exactly 1 (eg, if you are merely trying to check for the output line myApplication and you expect it never to appear more than once) then just do:

 ps -ef | grep myApplication > /dev/null && echo true 

(If you need the variable counter set for later processing, neither of these solutions will be appropriate.)

Using short circuited && and || operators is often much clearer than embedding if/then constructs, especially in one-liners.

like image 29
William Pursell Avatar answered Sep 23 '22 19:09

William Pursell