【问题标题】:compare variables didn't always work correctly比较变量并不总是正常工作
【发布时间】:2021-04-02 17:14:46
【问题描述】:

我在 utils.sh 文件中有一个函数

function contains_elt() {

    local -n ARRAY=$1
    local ELT=$2
    contains_elt_res=false

    local i
    for i in "${!ARRAY[@]}"
    do
        echo "$i === $ELT"
        if [ $i = $ELT ] ; then
            echo "Elt $ELT exists"
            contains_elt_res=true
        fi
    done
}

在另一个函数内的主脚本文件中调用:

function verify_lib_existance() {
    local -n array=$1

    if [ ${#array[@]} = 0 ] ; then
        printf "${RED} libs can not be empty.${NC}\n"
        exit 1
    fi

    local i
    for i in "${array[@]}"
    do
        echo "elet = $i"
        contains_elt LIBS $i

        if [ $contains_elt_res = false ] ; then
            printf "${RED} the lib ${i} is not support right now.${NC}\n"
            printf "${GREEN}Please add it in the LIBS array in utils.sh file ${NC}:\n"
            exit 1
        fi
    done
}

问题出在第一个函数内部,并且恰好在 if 语句中,比较不稳定,当我使用 read 获取输入时,有时它可以正常工作,有时不能正常工作,您会看到在 if 之前的行,我放置了一个 echo,我看到值是相同的,但是 if 没有正常工作。

【问题讨论】:

  • 检查空格、回车、ansi 转义和类似的值。这些都导致echo 显示相同的输出,即使值不同。
  • 请在您的代码中添加一个 shebang,然后将其粘贴到 shellcheck.net 并尝试实施那里提出的建议。

标签: bash quotes


【解决方案1】:

用双引号将所有变量引用括起来。

function contains_elt() {
    local -n ARRAY="$1"
    local ELT="$2"
    contains_elt_res=false

    local i
    for i in "${!ARRAY[@]}"
    do
        echo "$i === $ELT"
        if [ "$i" = "$ELT" ] ; then
            echo "Elt $ELT exists"
            contains_elt_res=true
        fi
    done
}

function verify_lib_existance() {
    local -n array="$1"

    if [ "${#array[@]}" = 0 ] ; then
        printf "${RED} libs can not be empty.${NC}\n"
        exit 1
    fi

    local i
    for i in "${array[@]}"
    do
        echo "elet = $i"
        contains_elt LIBS "$i"

        if [ "$contains_elt_res" = false ] ; then
            printf "${RED} the lib ${i} is not support right now.${NC}\n"
            printf "${GREEN}Please add it in the LIBS array in utils.sh file ${NC}:\n"
            exit 1
        fi
    done
}

【讨论】:

  • 我已经尝试过了,但总是同样的问题。如果我添加整个两个文件,你怎么看?
  • 你听从@Cyrus 的建议了吗?
猜你喜欢
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2019-07-10
相关资源
最近更新 更多