【问题标题】:Bash string comparison not workingBash字符串比较不起作用
【发布时间】:2012-01-22 04:50:51
【问题描述】:

我有以下 Bash 函数:

checkForUpdates() {
    checkLatest
    ret=$?
    if [ $ret != 0 ]; then
        return $ret
    fi
    count=0
    for i in $(ssh $__updateuser@$__updatehost "ls $__updatepath/*${latest}*"); do
        file="${i##$__updatepath}"
        echo "$file" >> $__debuglog
        if [ -f $__pkgpath/$file ]; then
            remoteHash=$(ssh $__updateuser@$__updatehost "md5sum -b < $__updatepath/${file}")
            localHash=$(md5sum -b < $__pkgpath/$file)
            echo "${remoteHash:0:32} = ${localHash:0:32}" >> $__debuglog
            if [ "${remoteHash:0:32}" != "${localHash:0:32}" ]; then
                files[$count]=$file
                count=$(($count + 1))
                echo "Hashes not matched, adding $i" >> $__debuglog
            fi
        else
            files[$count]=$file
            count=$(($count + 1))
            echo "$file missing" >> $__debuglog
        fi
    done

    # Verify that the files array isn't empty.
    if [ $count != 0 ]; then
        return 0
    else
        return 33
    fi
}

由于某种原因,remoteHash/localHash 比较总是返回 true。我添加了回声,以便我可以看到散列的值,它们肯定是不同的,我不知道我哪里出错了。我尝试了不同的运算符但没有成功,这让我发疯!

【问题讨论】:

  • 尝试使用bash -x &lt;command&gt;运行。
  • 不幸的是,我在这个脚本中大量使用了对话框,并且它不断删除输出。 -x 是否发送到标准输出或标准错误?如果它是 stderr,我可以将它通过管道传输到我相信的文件中。
  • 没关系,这是标准错误。
  • 不知道发生了什么,但它突然开始工作了。
  • 我讨厌这种情况发生!不错的代码顺便说一句。祝你好运。

标签: linux bash variables scripting ubuntu


【解决方案1】:

这与您的问题无关,但更多的是一般建议,首先也是最重要的you shouldn't parse the output of ls 而不是使用find -print0 这是一个示例:http://mywiki.wooledge.org/BashFAQ/001

还可以考虑使用[[ 而不是[ 请参阅:http://mywiki.wooledge.org/BashFAQ/031

现在关于您的代码,这部分:

checkLatest
ret=$?
if [ $ret != 0 ]; then
    return $ret
fi

可以简单写成:

checkLatest || return

并且您不需要在数组的索引上保留一个计数器,如果您将 var 初始化为像 files=() 这样的空数组,您可以使用 files+=("$file") 将元素附加到它,您可以使用"${#files[@]}"

【讨论】:

  • 非常感谢您的建议。不幸的是,我不再有时间来维护脚本,但我一定会在以后的项目中记住这些输入。
猜你喜欢
  • 2012-12-06
  • 1970-01-01
  • 2011-09-20
  • 2014-04-03
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多