ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Linux-Bash字符串比较无法正常工作

2019-12-02 01:51:17  阅读:298  来源: 互联网

标签:bash variables ubuntu scripting linux


我有以下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.我添加了回声,以便可以看到哈希值,并且它们肯定是不同的,而且我无法弄清楚哪里出了问题.我尝试过不同的运算符都没有成功,这让我发疯!

解决方法:

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

标签:bash,variables,ubuntu,scripting,linux
来源: https://codeday.me/bug/20191202/2084814.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有