if pgrep apache; then echo "oliver"; fi
如果命令pgrep apache
不为空,则会回显oliver
。我想做相反的事。如果命令pgrep apache
返回空字符串,请运行命令。如果shell命令为空
0
A
回答
4
1
试着这样做:
pgrep &>/dev/null apache || echo "foobar"
或:
if ! pgrep &>/dev/null apache; then echo "foobar"; fi
!
代表不
这不是基于命令的输出,但如果命令whas true
或false
。
在shell,当命令的返回码是0
,它被认为是true
,如果大于0,这是false
。您可以检查此返回码与变量$?
,例如:
ls /path/to/inexistant/file
echo $?
+0
但我的名字是'oliver'! – onassar 2013-02-18 19:16:41
+1
请勿*使用'&>'。语法是不明确的:''bash'会把它看成和'>/dev/null 2>&1'一样,而'dash'会把它当作'&>'(它会在后台运行进程,然后截断'/ dev/null') – 2013-02-19 00:13:16
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
回声不会发生,因为'pgrep apache'不是空的。而是因为'pgrep'成功返回而被执行。在这种情况下,成功的命令和产生某些输出的命令是等同的,但这是混淆的常见原因。 – 2013-02-19 00:15:34