Bash字符串(命令输出)相等测试

前端之家收集整理的这篇文章主要介绍了Bash字符串(命令输出)相等测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的脚本来检查网页是否包含指定的字符串.看起来像:
  1. #!/bin/bash
  2. res=`curl -s "http://www.google.com" | grep "foo bar foo bar" | wc -l`
  3. if [[ $res == "0" ]]; then
  4. echo "OK"
  5. else
  6. echo "Wrong"
  7. fi

正如你所看到的,我希望得到“OK”,但得到了“错误”.

它出什么问题了?

如果我使用if [$res ==“0”],它可以工作.如果我只使用res =“0”而不是res = curl …,它也可以获得所需的结果.

为什么会有这些差异?

您可以看到res包含的内容:echo“Wrong:res => $res<” 如果你想看看某些文本是否包含其他文本,你不必查看grep输出的长度:你应该看一下grep的返回码:
  1. string="foo bar foo bar"
  2. if curl -s "http://www.google.com" | grep -q "$string"; then
  3. echo "'$string' found"
  4. else
  5. echo "'$string' not found"
  6. fi

甚至没有grep:

  1. text=$(curl -s "$url")
  2. string="foo bar foo bar"
  3. if [[ $text == *"$string"* ]]; then
  4. echo "'$string' found"
  5. else
  6. echo "'$string' not found in text:"
  7. echo "$text"
  8. fi

猜你在找的Bash相关文章