Bash 变量是否包含变量
我试过几种方法,但都没能奏效 我有一个数组元素,我想检查它是否包含一个变量Bash 变量是否包含变量,bash,echo,ifs,Bash,Echo,Ifs,我试过几种方法,但都没能奏效 我有一个数组元素,我想检查它是否包含一个变量 if test "${${newpool[$a]}#*$pool}" != "${newpool[$a]}" ;then echo ${newpool[$a]} fi 我需要知道${newpool[$a]}是否包含$pool 我还尝试了一种使用函数发布的不同方法,但它也不起作用 contains() { string="$1" substring="$2" if test "${string#*$sub
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
使用Bashism:
contains() {
local string=$1 substring=$2
[[ $string = *"$substring"* ]]
}
在POSIX sh中:
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
向您的问题添加declare-p newpool pool a
的输出。请看一看:顺便说一句,确保测试子字符串为*
的情况(在调用时用引号传递,因此不会被文件名列表替换)--它会破坏不小心引用的代码;help+=“这是一个测试”与help=()绝对不同;帮助+=(“这是一个测试”)
。尝试将help+=“这是另一个测试”
和help+=“这是另一个测试”)
放在后面——第一个将把字符串附加到数组中的第一个元素,第二个将附加一个新元素。