0

if pgrep apache; then echo "oliver"; fi
This will echo oliver if the command pgrep apache is not empty. I want to do the reverse. If the the command pgrep apache returns an empty string, run a command.

1
  • The echo does not happen because 'pgrep apache is not empty'. Rather, it is executed because pgrep returns successfully. In this case, the command being successful and the command generating some output are equivalent, but this is a common source of confusion. Commented Feb 19, 2013 at 0:15

3 Answers 3

4
if ! pgrep apache; then echo "oliver"; fi
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly what I was looking for. Thanks DigitalRoss.
1

Try doing this :

pgrep &>/dev/null apache || echo "foobar"

or :

if ! pgrep &>/dev/null apache; then echo "foobar"; fi

! stands for NOT

this is not based on the output of the command but if the command whas true or false.

In , when the return code of a command is 0, it's considered true, if more than 0, it's false. You can check this return code with the variable $?, example :

ls /path/to/inexistant/file
echo $?

See true & false commands

1 Comment

Do not use &>. The grammar is ambiguous: bash will treat it the same as >/dev/null 2>&1, while dash will treat it as & > (it will run the process in the backround, and then truncate /dev/null)
1

I'm unsure of the context but presuming you want to do something a particular process is or is not found.

bash-3.2$ pgrep -q bash &&  echo "bash was found"
bash was found

bash-3.2$ pgrep -q XXXbash ||  echo "XXXbash was NOT was found"
XXXbash was NOT was found

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.