Linux 是否可以在“if”语句中通过管道传输多个命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20612891/
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
Is it possible to pipe multiple commands in an 'if' statement?
提问by XOR
Part of a script I'm writing needs to check various text files for the same strings. Before I just had to check one file so I had a long list of strings within cateogies to search for which are defined as variables. Later on in the script the variabled are called and output to the screen if there is a match:
我正在编写的脚本的一部分需要检查相同字符串的各种文本文件。在我只需要检查一个文件之前,我在类别中有一长串字符串来搜索哪些被定义为变量。稍后在脚本中调用变量并在匹配时输出到屏幕:
category_1=$(sudo zcat myfile | egrep -c 'Event 1|Event 2|Event 3')
category_2=$(sudo zcat myfile | egrep -c 'Event 4|Event 5|Event 6')
category_3=$(sudo zcat myfile | egrep -c 'Event 7|Event 8|Event 9')
...
echo Category 1
if [[ $category_1 -ge 2 ]];then
echo There were $category_1 events
elif [[ $category_1 -eq 1 ]]; then
echo There was $category_1 event
fi
etc, etc...
等等等等...
Now I need to change it so that I can check the grepped strings against multiple text files. I've tried to define the new files as variables and pipe them in the if statement with the grep variable to no avail:
现在我需要更改它,以便我可以针对多个文本文件检查 grepped 字符串。我试图将新文件定义为变量,并在 if 语句中使用 grep 变量将它们通过管道传输,但无济于事:
category_1=$(egrep -c 'Event 1|Event 2|Event 3')
category_2=$(egrep -c 'Event 4|Event 5|Event 6')
category_3=$(egrep -c 'Event 7|Event 8|Event 9')
myfile=$(sudo zcat myfile)
myfile2=$(sudo zcat myfile2)
myfile3=$(sudo zcat myfile3)
...
echo Category 1 - Myfile
if [[ myfile | $category_1 -ge 2 ]];then
echo There were $category_1 events in myfile
elif [[ myfile | $category_1 -eq 1 ]]; then
echo There was $category_1 event in myfile
fi
It seems that I can't pipe commands in an if statement.
似乎我无法在 if 语句中使用管道命令。
采纳答案by choroba
Use $(...)
to capture output of a command into a string:
用于$(...)
将命令的输出捕获到字符串中:
if [[ $(sudo zcat myfile1 | egrep -c 'Event 1|Event 2|Event 3') -ge 2 ]] ; then
回答by Igor Chubin
You can use pipes in if
, but you mix two things.
You use $category_1
with pipe; and $category_1
is not a command.
You can use a command substitution instead of the variable.
你可以在 中使用管道if
,但你混合了两件事。你$category_1
和管道一起使用;并且$category_1
不是命令。您可以使用命令替换代替变量。
if [[ `sudo zcat myfile | egrep -c 'Event 1|Event 2|Event 3')` -ge 2 ]];then
and so on.
等等。
You can also use variables instead of commands, but it will be a little bit strange.
也可以用变量代替命令,但会有点奇怪。
回答by Nicki Johanna
You could instead use a command such as: if [ "$house" = "nice" ]||[ "$house" = "bad" ] then... to do the job
您可以改为使用如下命令: if [ "$house" = "nice" ]||[ "$house" = "bad" ] then... 来完成这项工作