Bash 比较输出而不是命令

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

Bash compare output rather than command

bashstring-comparison

提问by moztech

Trying to create a script to read a remote file and check the md5 checksum and alert if a mismatch yet getting an error I can't understand.

尝试创建一个脚本来读取远程文件并检查 md5 校验和,并在不匹配时发出警报,但我无法理解。

#!/bin/sh
REMOTEMD5=$(ssh user@host 'md5sum file.txt')
LOCALMD5=$(md5sum 'file.txt')
if [$LOCALMD5 !== $REMOTEMD5]
then
  echo "all OK"
else
  echo -e "no match, Local:"$LOCALMD5"\nRemote:"$REMOTEMD5
fi

This returns line 4: [6135222a12f06b2dfce6a5c1b736891e: command not found

这返回 line 4: [6135222a12f06b2dfce6a5c1b736891e: command not found

I've tried using ' or " around the $LOCALMD5 but never seem able to get this to compare the outputs. What am I doing wrong? Thanks

我试过在 $LOCALMD5 周围使用 ' 或 " 但似乎永远无法得到它来比较输出。我做错了什么?谢谢

回答by Joachim Isaksson

Try;

尝试;

if [ "$LOCALMD5" == "$REMOTEMD5" ]

which should work better.

哪个应该工作得更好。

Edit: I think you got == and != reversed in your code.

编辑:我认为你的代码中 == 和 != 颠倒了。

回答by Mithrandir

I think it should be like this:

我觉得应该是这样的:

#!/bin/sh
REMOTEMD5=$(ssh user@host 'md5sum file.txt')
LOCALMD5=$(md5sum 'file.txt')
if [ "$LOCALMD5" == "$REMOTEMD5" ]
then
  echo "all OK"
else
  echo -e "no match, Local:"$LOCALMD5"\nRemote:"$REMOTEMD5
fi

The space between the bracket and the value is important!

括号和值之间的空格很重要!

回答by Kyle Jones

[isn't bash syntax, it is a command. So you must have a space between it and its first argument $LOCALMD5. There also needs to be a space between $REMOTEMD5and ].

[不是 bash 语法,它是一个命令。所以你必须在它和它的第一个参数之间有一个空格$LOCALMD5$REMOTEMD5和之间也需要有一个空格]