我试图让一个脚本给我多个单词和单词变体的输出。我尝试为变量添加 -o,引用单词,将它们通过管道连接在一起。每个 varname 的单词是我想要输出给我的指示单词。有没有办法纠正这个问题,或者每个变量都需要单独设置吗?如varname1=even varname2=Even varname3=EVEN等。
#!/bin/bash
varname1=even -o Even -o EVEN
varrname2=odd -o Odd -o ODD
varname3=zero -o Zero -o ZERO
varname4=negative -o Negative -o NEGATIVE
# Ask the user for one of four select words
echo "Type one of the following words:"
echo "even, odd, zero, negative"
read varword
if [[ ("$varword" = $varname1 ) || ("$varword" = $varname2 ) || ("$varword" = $varname3 ) || ("$varword" = $varname4 ) ]]
then
echo "The approved word you have selected is $varword, great work! "
else
echo "The unapproved word you have selected is $varword, Please try again."
fi
答案1
echo "Type one of the following words:"
echo "even, odd, zero, negative"
while :; do
read varword
varword="${varword,,}" #downcase it
case "$varword" in
even|odd|zero|negative)
echo "The approved word you have selected is $varword, great work! "; break;;
*)
echo "The unapproved word you have selected is $varword, Please try again.";;
esac
done
答案2
在一个变量中存储多个值的一种方法是数组。这是有关如何在 bash 中使用数组变量的文档。
然而,在我看来,你想要的是不区分大小写的匹配。这可以通过 来实现grep -iq
。i
告诉 grep 匹配不区分大小写,并q
告诉 grep 它应该只返回 true 或 false。另外,您可以\|
在 grep 子句中使用 or 运算符来匹配多个单词。最后,您使用这里字符串符号 <<< 将变量直接提供给 grep。这大大简化了您的脚本:
#!/bin/bash
# Ask the user for one of four select words
echo "Type one of the following words:"
echo "even, odd, zero, negative"
read varword
if grep -iq "even\|odd\|zero\|negative" <<< "$varword"
then
echo "The approved word you have selected is $varword, great work! "
else
echo "The unapproved word you have selected is $varword, Please try again."
fi