我像这样运行我的脚本
./test.sh -c "red blue yellow"
./test.sh -c "red blue"
在 bash 中,变量“color”将被分配为“red blue yellow”或“red blue”
echo $collor
red blue yellow
两个问题:
A:“红色”对我来说是一个重要的参数,我怎么知道红色是否包含在可变颜色中?
if [ red is in color] ; then "my operation"
B: 我有一个只有 3 种颜色的颜色列表,我如何检查是否有未定义的颜色传递给脚本
./test.sh -c "red green yellow"
如何定义颜色列表以及如何进行检查以便获得打印件
Warnings: wrong color is green is passed to script
谢谢
最佳答案
(A) 可以使用通配符字符串比较来处理:
if [[ "$color" = *red* ]]; then
echo 'I am the Red Queen!'
elif [[ "$color" = *white* ]]; then
echo 'I am the White Queen!'
fi
这种方法的问题在于它不能很好地(或根本)处理单词边界; red
会触发第一个条件,但 orange-red
和 bored
也会触发。此外,(B) 将很难(或不可能)以这种方式实现。
处理此问题的最佳方法是将颜色列表分配给 Bash array :
COLORS=($color)
for i in "${COLORS[@]}"; do
if [[ "$i" = "red" ]]; then
echo 'I am the Red Queen!'
elif [[ "$i" = "white" ]]; then
echo 'I am the White Queen!'
fi
done
然后您可以使用嵌套循环遍历另一个包含允许颜色的数组,并报告在那里找不到的任何输入颜色。
关于linux - 如何检查参数是否包含某些单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343478/