LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   pgrep "program" and if statement (https://www.linuxquestions.org/questions/linux-newbie-8/pgrep-program-and-if-statement-913666/)

ted_chou12 11-15-2011 09:50 AM

pgrep "program" and if statement
 
Hi, I don't know why this always returns the false boolean:
Code:

if [ ! -z $(pgrep "mediatomb") ] ; then
                        mtstatus="Mediatomb is running!"
                else
                        mtstatus="Mediatomb is not running!"
                fi

I tried:
Code:

echo $(pgrep "mediatomb")
1222 1223 1224 1225 1230 1232 1234 1236 1237 1238 1975 1979 1980 1981

Thanks,
Ted

colucix 11-15-2011 10:04 AM

The command substitution is performed before the test take places, so that it actually is something like:
Code:

if [ ! -z 1222 1223 1224 1225 1230 1232 1234 1236 1237 1238 1975 1979 1980 1981 ] ; then
This should throw an error for too many arguments or binary operator expected. Anyway, what you really need is
Code:

if pgrep bash; then
that checks the exit status of the pgrep command: when processes are found the exit status is 0 (success) and the test is true, when processes don't exist, the exit status is 1 (failure) and the test is false. Anyway, I cannot explain why your test doesn't throw an error message and returns always false.

Moreover note that ! -z is the same as -n (the length of string is nonzero).

ted_chou12 11-15-2011 12:04 PM

Quote:

Originally Posted by colucix (Post 4524689)
The command substitution is performed before the test take places, so that it actually is something like:
Code:

if [ ! -z 1222 1223 1224 1225 1230 1232 1234 1236 1237 1238 1975 1979 1980 1981 ] ; then
This should throw an error for too many arguments or binary operator expected. Anyway, what you really need is
Code:

if pgrep bash; then
that checks the exit status of the pgrep command: when processes are found the exit status is 0 (success) and the test is true, when processes don't exist, the exit status is 1 (failure) and the test is false. Anyway, I cannot explain why your test doesn't throw an error message and returns always false.

Moreover note that ! -z is the same as -n (the length of string is nonzero).


Thanks for reminding, I realized that double quote should be made:
Code:

if [ ! -z "$(pgrep "mediatomb")" ] ; then
                        mtstatus="Mediatomb is running!"
                else
                        mtstatus="Mediatomb is not running!"
                fi



All times are GMT -5. The time now is 11:58 PM.