linux - 如何检查参数是否包含某些单词

标签 linux bash arguments

我像这样运行我的脚本

./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-redbored 也会触发。此外,(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/

相关文章:

Python 函数可选参数 - 可以添加为条件吗?

r - dplyr 句点字符 "."指的是什么?

java - 如何从 Java 启动交互式命令行界面程序?

java - 从java运行grep命令后获取错误

linux - 使用 Bash 和 GNU 工具将 GMT 时间戳转换为本地时间

linux - 猫 |在 bash 中按名称对 csv 文件进行排序

python - 错误 - 输入最多 1 个参数,得到 3 个

c - 除了 pthread_create 在 linux 上创建 linux 线程的方法

linux - 如果行长于 x 个字符,则剪切并添加字符串

c++ - 为 Windows cmd 添加 argc