Linux Bash shell 'if' 语句比较来自不同命令的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7850631/
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-08-05 06:47:16  来源:igfitidea点击:

Bash shell 'if' statement comparing outputs from different commands

linuxbashshellif-statementgrep

提问by bikerben

Using an adapted example given to me by Sam Rubywhich I have tweaked so I can show what I'm trying to achieve.

使用Sam Ruby 给我的一个改编示例,我对其进行了调整,以便我可以展示我想要实现的目标。

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
if [$app1 = (someapptwo -flag | grep usefulstuff | cut -c 20-25)]; then
mkdir IPFolder-1
elif ...blah blah
fi 

Can I use grep as show above or am I barking up the wrong tree? or should it look a little some thing like this:

我可以使用上面显示的 grep 还是我吠错了树?或者它应该看起来像这样:

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
app2=$(someapptwo -flag | grep usefulstuff | cut -c 20-25)
if [$app1 = $app2]; then
mkdir IPFolder-1
elif ...blah blah
fi 

回答by milancurcic

You need to refer to the value of your expression by prepending a $:

您需要在前面加上 $ 来引用表达式的值:

...
if [ "$app1" = "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]; then
...

回答by Jonathan Leffler

At least in other shells, you need to be a lot more careful with spaces; the square bracket is a command name and needs to be separated from previous and following words. You also need (again in classic shells for certain) to embed the variables in double quotes:

至少在其他 shell 中,您需要对空格更加小心;方括号是命令名,需要与前后单词分开。您还需要(再次在经典 shell 中)将变量嵌入双引号中:

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
if [ "$app1" = "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

You could do it all in one line (well, two because I avoid the horizontal scrollbar whenever possible):

您可以在一行中完成所有操作(好吧,两行是因为我尽可能避免使用水平滚动条):

if [ "$(someapp    -flag | grep usefulstuff | cut -c  5-10)" = \
     "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

Or you could do it with two separate command captures:

或者您可以使用两个单独的命令捕获来完成:

app1=$(someapp    -flag | grep usefulstuff | cut -c  5-10)
app2=$(someapptwo -flag | grep usefulstuff | cut -c 20-25)
if [ "$app1" = "$app2" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

Update:Some extra quotes added. It would be possible to quote the assignments too:

更新:添加了一些额外的引号。也可以引用作业:

app1="$(someapp -flag | grep usefulstuff | cut -c  5-10)"

No harm would be done; it isn't strictly necessary with bash(but it may well have been necessary with archaic Bourne shell).

不会造成任何伤害;它不是绝对必要的bash(但对于古老的 Bourne shell 可能是必要的)。