如何在bash脚本

时间:2018-03-17 14:26:50

标签: bash shell unix getopts

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

我正在尝试在-c <component>的输入上强制执行字符串匹配(使用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

所以在我的测试中,我无法获得强制执行的字符串。

如果输错字符串,我希望得到usage

./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

所以我的问题是你将如何处理和检查正确的字符串输入? 有没有更好的方法来编写我的测试?

1 个答案:

答案 0 :(得分:1)

您正在测试错误的参数。 $c尚未定义,但您刚刚在-c中保存了$component个参数。

也就是说,另一个case声明可能比您的if条件更简单,并且不依赖于bash扩展。

case $component in
  customer_builder|\
  customer_service|\
  historic_customer_builder|\
  stream_builder|\
  data_distributor)
    :  # Do nothing
    ;;
  *)
    usage
    exit 1
    ;;
esac

好了,既然我已经从我的系统中尝试保持POSIX兼容,这里使用if&#39; s更简单[[...]]声明模式匹配能力。 (这将在较新版本的bash中按原样运行;旧版本需要shopt -s extglob才能启用@(...)语法。)

if [[ $component != @(customer_builder|customer_service|historic_customer_builder|stream_builder|data_distributor) ]]; then