Bash字符串比较不起作用

时间:2011-12-16 17:31:23

标签: linux bash variables scripting ubuntu

我有以下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。我添加了回声,以便我可以看到哈希的值,它们肯定是不同的,我无法弄清楚我哪里出错了。我尝试过不同的操作员但没有成功,这让我发疯了!

1 个答案:

答案 0 :(得分:3)

这与您的问题无关,但更多的是一般性建议,首先是最重要的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[@]}"

获取计数