如何为参数提供条件

如何为参数提供条件

在提供外部参数值时,前后应有连字符。如果连字符不存在,它应该反映错误,指出文本之前和之后都需要连字符。

例如:外部参数应该是

-report-country-sales-price-

答案1

在类似 POSIX 的 shell 中,例如bash,您可以执行以下操作:

case $1 in
  (-*-) ;; # OK
  (*) echo >&2 "The first parameter must start and end with a -"; exit 1
esac

对于更具体的匹配,具体来说bash

regex='^-([[:alpha:]]+)-([[:alpha:]]+)-([[:alpha:]]+)-([[:alpha:]]+)-$'
if [[ $1 =~ $regex ]]; then
  A=${BASH_REMATCH[1]}
  B=${BASH_REMATCH[2]}
  C=${BASH_REMATCH[3]}
  D=${BASH_REMATCH[4]}
else
  echo >&2 "First parameter must be -letters-letters-letters-letters-"
  exit 1
fi

或者允许可变数量的-分隔单词:

regex='^(-[[:alpha:]]+){2,6}-$'
if [[ $1 =~ $regex ]]; then
  IFS=- read -ra words <<< "$1" # OK here as $1 is guaranteed not to
                                # contain newline characters at this
                                # point.
  A=${words[1]}
  B=${words[2]}
  C=${words[3]-not-supplied}
  D=${words[4]-not-supplied}
  E=${words[5]-not-supplied}
  F=${words[6]-not-supplied}
else
  echo >&2 "First parameter must be list of 2 to 6 - separated words"
  exit 1
fi

相关内容