如何在bash脚本中使用getopts有效地测试有效的字符串输入

如何在bash脚本中使用getopts有效地测试有效的字符串输入,bash,shell,unix,getopts,Bash,Shell,Unix,Getopts,我在bash脚本中使用getopts传递2个参数 我正在尝试对输入的-c强制执行字符串匹配(使用if语句),以输入以下选项: 注意:它必须与以下5个选项的确切字符串相匹配: customer_builder customer_service historic_customer_builder stream_builder data_distributor 正在进行的代码: # Usage for getopts usage () { echo -e "Usage:$0 -r regio

我在bash脚本中使用
getopts
传递2个参数

我正在尝试对输入的
-c
强制执行字符串匹配(使用if语句),以输入以下选项:

注意:它必须与以下5个选项的确切字符串相匹配:

customer_builder
customer_service
historic_customer_builder
stream_builder
data_distributor
正在进行的代码:

# Usage for getopts
usage () {
    echo -e "Usage:$0 -r region -c <component>"
    echo -e "Available components:"
    echo -e "customer_builder|customer_service|historic_customer_builder|stream_builder|data_distributor"
    echo -e "Example:$0 -r us-east-1 -c customer_builder"
}

while getopts ":r:c:" opt; do
  case $opt in
    r) region="$OPTARG";;
    c) component="$OPTARG"
       if [[ "${c}" != "customer_builder" && "${c}" != "customer_service" && "${c}" != "historic_customer_builder" && "${c}" != "stream_builder" && "${c}" != "data_distributor" ]]; then
         usage
         exit 1
       fi
       ;;
    *) usage
       exit 1
       ;;
  esac
done
   if [[ "${c}" != "customer_builder" && "${c}" != "customer_service" && "${c}" != "historic_customer_builder" && "${c}" != "stream_builder" && "${c}" != "data_distributor" ]]; then
     usage
     exit 1
   fi
因此,在我的测试中,我无法强制执行字符串

如果我输入的字符串不正确,我希望得到
用法

./script.sh -r us-east-1 -c customer-builder
./script.sh -r us-east-1 -c customer
./script.sh -r us-east-1 -c builder
./script.sh -r us-east-1 -c foo_bar
但是,如果输入正确,我希望脚本能够执行:

./script.sh -r us-east-1 -c customer_builder
./script.sh -r us-east-1 -c customer_service
./script.sh -r us-east-1 -c stream_builder
所以我的问题是,您将如何处理和检查正确的字符串输入?
是否有更好的方法编写我的测试?

您测试的参数错误<代码>$c未定义,但您只是将
-c
的参数保存在
$component


也就是说,另一个
case
语句可能比long
if
条件更简单,并且不依赖于
bash
扩展

case $component in
  customer_builder|\
  customer_service|\
  historic_customer_builder|\
  stream_builder|\
  data_distributor)
    :  # Do nothing
    ;;
  *)
    usage
    exit 1
    ;;
esac
好的,现在我已经尝试在我的系统之外保持POSIX兼容,下面是一个更简单的
if
语句,使用
[…]
的模式匹配功能。(这将与较新版本的
bash
一样有效;较旧版本需要
shopt-s extglob
才能启用
@(…)
语法。)


谢谢你的意见。对于
if
语句,我希望测试它是否不是这些选项中的任何一个,然后转到
用法
-我们需要添加
=啊,对。是的,使用
=,或否定整个测试(
if![[$component=…];然后
)。
if [[ $component != @(customer_builder|customer_service|historic_customer_builder|stream_builder|data_distributor) ]]; then