Bash - 比较两个命令的输出

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

Bash - comparing output of two commands

linuxbashcurlterminalstring-comparison

提问by antoninkriz

I have this code:

我有这个代码:

#!/bin/bash

CMDA=$(curl -sI website.com/example.txt | grep Content-Length)

CMDB=$(curl -sI website.com/example.txt | grep Content-Length)

if [ "CMDA" == "CMDB" ];then
  echo "equal";
else
  echo "not equal";
fi

with this output

有了这个输出

root@abcd:/var/www/html# bash ayy.sh
not equal

which should be "equal" instead of "not equal". What did I do wrong?

这应该是“相等”而不是“不相等”。我做错了什么?

Thnaks

纳克斯

回答by janos

You forgot the $for the variables CMDAand CMDBthere. This is what you need:

你忘记了$变量CMDACMDB那里。这是你需要的:

if [ "$CMDA" = "$CMDB" ]; then

I also changed the ==operator to =, because man testonly mentions =, and not ==.

我也将==运算符更改为=,因为man test只提到了=,而不是==

Also, you have some redundant semicolons. The whole thing a bit cleaner:

此外,您还有一些多余的分号。整个事情更干净一点:

if [ "$CMDA" = "$CMDB" ]; then
  echo "equal"
else
  echo "not equal"
fi

回答by Aus

You are comparing string "CMDA" with "CMDB", you should instead compare the variables using $ like ${CMDA}

您正在将字符串“CMDA”与“CMDB”进行比较,您应该使用 $ like ${CMDA} 来比较变量