Bash:一行中的 If/Else 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17203122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:51:26  来源:igfitidea点击:

Bash: If/Else statement in one line

bash

提问by Arthur Rimbun

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.

我试图检查一个进程(假设它被调用some_process)是否正在服务器上运行。如果是,则回显 1,否则回显 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

Note:The [s]in some_proces[s]is to prevent grepfrom returning itself.

注:[s]some_proces[s]是防止grep从返回本身。

If some_processis running, then "1"gets echoed, which is fine. However, if some_processis not running, nothing gets echoed.

如果some_process正在运行,则"1"得到回显,这很好。但是,如果some_process没有运行,则没有任何回显。

回答by William Pursell

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:

请注意,这依赖于 echo 不会失败,这当然不能保证。更可靠的写法是:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

回答by ruakh

&&means "and if successful"; by placing your ifstatement on the right-hand side of it, you ensure that it will only run if grepreturns 0. To fix it, use ;instead:

&&意思是“如果成功”;通过将您的if语句放在它的右侧,您可以确保它仅在grepreturn 时运行0。要修复它,请;改用:

ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi

ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi

(or just use a line-break).

(或只是使用换行符)。

回答by John Gilmer

Use grep -vcto ignore grepin the psoutput and count the lines simultaneously.

使用grep -vc忽视grepps输出,同时计数线。

if [[ $(ps aux | grep process | grep -vc grep)  > 0 ]] ; then echo 1; else echo 0 ; fi

回答by Costi Ciudatu

You can make full use of the &&and ||operators like this:

您可以像这样充分利用&&and||运算符:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

为了排除 grep 本身,您还可以执行以下操作:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0

回答by once

pgrep -q some_process && echo 1 || echo 0

more oneliners here

这里有更多的oneliners