【问题标题】:does variable contain variable变量是否包含变量
【发布时间】:2017-08-15 19:47:53
【问题描述】:

我尝试了几件事,但无法让它发挥作用。

我有一个数组元素,我想检查它是否包含变量

if test "${${newpool[$a]}#*$pool}" != "${newpool[$a]}" ;then
        echo ${newpool[$a]}
fi

我需要知道 ${newpool[$a]} 是否包含 $pool

我还尝试了使用函数发布的另一种方法,但它也不起作用

contains() {
string="$1"
substring="$2"
if test "${string#*$substring}" != "$string"
then
    return 0    # $substring is in $string
else
    return 1    # $substring is not in $string
fi
}

help=()
help+="this is a test"
i="test"

test=$(contains ${help[0]} $i)

if [[ $test == 0 ]];then
    echo ${help[0]}
fi 

【问题讨论】:

  • declare -p newpool pool a 的输出添加到您的问题中。
  • 请看:shellcheck.net
  • 顺便说一句,请务必测试您的子字符串为 * 的情况(在调用时用引号传递,因此它不会被文件名列表替换)——它会破坏代码不小心引用。
  • 另外,help=(); help+="this is a test" 绝对不help=(); help+=( "this is a test" ) 相同。尝试将help+="this is another test"help+=( "this is another test" ) 放在后面——第一个将字符串附加到数组中的第一个元素,第二个将附加一个新元素。

标签: bash echo ifs


【解决方案1】:

使用 bashisms:

contains() {
  local string=$1 substring=$2
  [[ $string = *"$substring"* ]]
}

在 POSIX 中:

contains() {
  string=$1; substring=$2
  case $string in
    *"$substring"*) return 0;;
    *)              return 1;;
  esac
}

无论哪种情况:

if contains foobar oo; then  echo "foobar contains oo"; fi
if contains foobar baz; then echo "foobar contains baz"; fi

只会正确地发出foobar contains oo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2018-06-29
    • 2011-04-09
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多