如果shell命令为空

时间:2013-02-18 19:14:22

标签: shell

if pgrep apache; then echo "oliver"; fi
如果命令oliver不为空,这将回显pgrep apache。我想反过来。如果命令pgrep apache返回空字符串,请运行命令。

3 个答案:

答案 0 :(得分:4)

if ! pgrep apache; then echo "oliver"; fi

答案 1 :(得分:1)

尝试这样做:

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

或:

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

!代表 NOT

这不是基于命令的输出,但是如果命令有truefalse

中,当命令的返回码为0时,它被视为true,如果大于0,则为false。您可以使用变量$?检查此返回代码,例如:

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

请参阅true & false commands

答案 2 :(得分:1)

我不确定上下文,但假设你想做某件特定的过程已经找到或找不到。

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