我有一个脚本可以为变量
指定名称列表$a = tom jerry albert yoyo etc
我需要检查脚本中另一个变量的内容是否与分配给此变量的名称之一匹配。我怎样才能做到这一点?我的另一个变量名是$name
。所以我的逻辑应该是。
if $name contains in $a
echo it matches
esle
echo it does not match
fi
我的$name
等于汤姆,我喜欢echo
“匹配”
由于
答案 0 :(得分:0)
您可以遍历$ list变量并检查匹配项,如以下摘录:
list="tom jerry albert yoyo etc"
name=tom
for item in $list
do
if [[ "$item" == "$name" ]]
then
echo it matches
else
echo it does not match
fi
done
答案 1 :(得分:0)
理想情况下,您可能希望使用数组来存储名称并迭代它以测试匹配:
#!/bin/bash
contains()
{
local element
for element in "${@:2}"; do
[ "${element}" = "$1" ] && return 0
done
return 1
}
a=(tom jerry albert yoyo)
for name in tom to foo; do
if contains "${name}" "${a[@]}"; then
echo "${name} matches"
else
echo "${name} doesn't match"
fi
done
$ ./t.sh
tom matches
to doesn't match
foo doesn't match
你甚至可以通过"参考"通过使用变量间接,这样你只需要将数组的名称传递给你想要匹配的contains
:
contains()
{
local element
for element in "${!1}"; do
[ "${element}" = "$2" ] && return 0
done
return 1
}
names=(tom jerry albert yoyo)
for name in tom to foo; do
if contains "names" "${name}"; then
echo "${name} matches"
else
echo "${name} doesn't match"
fi
done
答案 2 :(得分:0)
对于完全可移植的解决方案,您可以使用case
。像
case " $list " in
*" $name "* ) echo "'$name' included in '$list'" ;;
* ) echo not. ;;
esac
答案 3 :(得分:-1)
好的,我找到了答案
if [[ "$a" =~ "$name" ]] && [ -n "$name" ]; then
echo it matches
else
echo it does not match
fi
干杯