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
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.
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.
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.
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"
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.
In fact, you can do one better by using pgrep
:
if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With