Bash:If/Else语句一行 [英] Bash: If/Else statement in one line
问题描述
我正在尝试检查服务器上是否正在运行某个进程(假定它称为some_process
).如果是,则回显1,否则回显0.
I am trying to check if a process (assume it is called some_process
) is running on a server. If it is, then echo 1, otherwise echo 0.
这是我正在使用的命令,但仅部分起作用(下面有更多信息).请注意,我需要将脚本编写成一行.
This is the command that I am using but it only works partially (more info below). Note that I need to write the script in one line.
ps aux | grep some_proces[s] > /tmp/test.txt && if [ $? -eq 0 ]; then echo 1; else echo 0; fi
注意:some_proces[s]
中的[s]
是为了防止grep
返回自身.
Note: The [s]
in some_proces[s]
is to prevent grep
from returning itself.
如果some_process
正在运行,则回显"1"
,这很好.但是,如果some_process
没有运行,则不会回显任何内容.
If some_process
is running, then "1"
gets echoed, which is fine. However, if some_process
is not running, nothing gets echoed.
推荐答案
无需显式检查$?
.只要做:
There is no need to explicitly check $?
. Just do:
ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0
请注意,这依赖于回声不会失败,这肯定不能得到保证.一种更可靠的书写方式是:
Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:
if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi
这篇关于Bash:If/Else语句一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!