【问题标题】:How to check if certain words is contained by an argument or not如何检查某些单词是否包含在参数中
【发布时间】:2013-10-21 00:42:26
【问题描述】:

我像

一样运行我的脚本
./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

谢谢

【问题讨论】:

    标签: linux bash arguments


    【解决方案1】:

    A:“红色”对我来说是一个重要的参数,我怎么知道红色是不是 包含在可变颜色中?

    你可以说:

    if [[ "$2" == *red* ]]; then
      echo "Color red is present ..."
    fi
    

    仅当颜色 red 包含在脚本的参数 (./test.sh -c "red blue yellow") 中时,该条件才会成立。

    B:我有一个只有 3 种颜色的颜色列表,如何检查是否有 传递给脚本的未定义颜色

    colors=(red blue yellow)       # color list with three colors
    IFS=$' ' read -a foo <<< "$2"
    echo "${#foo[@]}"
    for color in "${foo[@]}"; do
      if [[ "${colors[@]}" != *${color}* ]]; then
        echo incorrect color $color
      fi
    done
    

    【讨论】:

      【解决方案2】:

      (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
      

      然后,您可以使用嵌套循环遍历另一个包含允许颜色的数组,并报告其中未找到的任何输入颜色。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2021-07-21
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多