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.
3 Answers
if ! pgrep apache; then echo "oliver"; fi
1 Comment
onassar
This was exactly what I was looking for. Thanks DigitalRoss.
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 shell, 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 $?
1 Comment
William Pursell
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)
pgrep apacheis not empty'. Rather, it is executed becausepgrepreturns successfully. In this case, the command being successful and the command generating some output are equivalent, but this is a common source of confusion.