Bash 字符串(命令输出)相等性测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12444125/
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
Bash string (command output) equality test
提问by kliu
I have a simple script to check whether webpage contains a specified string. It looks like:
我有一个简单的脚本来检查网页是否包含指定的字符串。看起来像:
#!/bin/bash
res=`curl -s "http://www.google.com" | grep "foo bar foo bar" | wc -l`
if [[ $res == "0" ]]; then
echo "OK"
else
echo "Wrong"
fi
As you can see, I am looking to get "OK", but got a "Wrong".
如您所见,我希望得到“OK”,但得到了“Wrong”。
What's wrong with it?
它出什么问题了?
If I use if [ $res == "0" ], it works. If I just use res="0" instead of res=curl..., it also can obtain the desired results.
如果我使用 if [ $res == "0" ],它会起作用。如果我只是使用 res="0" 而不是 res= curl...,它也可以获得所需的结果。
Why are there these differences?
为什么会有这些差异?
采纳答案by kliu
I found the answer in glenn Hymanman's help.
我在glenn Hymanman的帮助中找到了答案。
I get the following points in this question:
我在这个问题中得到以下几点:
wc -l's output contains whitespaces.- Debugging with
echo "$var"instead ofecho $var [[preserves the literal value of all characters within the var.[expands var to their values before perform, it's because [ is actually thetestcmd, so it follows Shell Expansionsrules.
wc -l的输出包含空格。- 使用
echo "$var"而不是调试echo $var [[保留 var 中所有字符的字面值。[在执行之前将 var 扩展为它们的值,这是因为 [ 实际上是testcmd,所以它遵循Shell Expansions规则。
回答by glenn Hymanman
You could see what rescontains: echo "Wrong: res=>$res<"
你可以看到什么res包含:echo "Wrong: res=>$res<"
If you want to see if some text contains some other text, you don't have to look at the lengthof grep output: you should look at grep's return code:
如果要查看某些文本是否包含其他文本,则不必查看grep 输出的长度:应该查看 grep 的返回代码:
string="foo bar foo bar"
if curl -s "http://www.google.com" | grep -q "$string"; then
echo "'$string' found"
else
echo "'$string' not found"
fi
Or even without grep:
或者甚至没有 grep:
text=$(curl -s "$url")
string="foo bar foo bar"
if [[ $text == *"$string"* ]]; then
echo "'$string' found"
else
echo "'$string' not found in text:"
echo "$text"
fi

