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