Bash 如何确定在getopts中是否传递了正确的参数?

Bash 如何确定在getopts中是否传递了正确的参数?,bash,getopts,Bash,Getopts,我有一个包含以下内容的bash脚本: while getopts ":a:1:2:3:4" arg; do case "$arg" in a) a=$OPTARG ;; 1) one=$OPTARG ;; 2) two=$OPTARG ;; 3) three=$OPTARG ;; 4) four=$OPTARG ;; 参数a有两个选项,假设它们是字符串“string1”或“string2”。如果a被指定为“st

我有一个包含以下内容的bash脚本:

while getopts ":a:1:2:3:4" arg; do

case "$arg" in

a)
    a=$OPTARG
    ;;
1)
    one=$OPTARG
    ;;
2)
    two=$OPTARG
    ;;
3)
    three=$OPTARG
    ;;
4)
    four=$OPTARG
    ;;
参数
a
有两个选项,假设它们是字符串
“string1”
“string2”
。如果
a
被指定为
“string1”
,则必须提供参数
1
2
。同样,如果
a
被指定为
“string2”
,则必须提供参数
3
4

在继续之前,我需要一种方法来验证用户是否指定了必要的参数。所以,在伪代码中,它类似于

if [ a == "string1" ]; then 

  if [1 and 2 were not given]; then

      echo "Arguments 1 and 2 were not given"
      exit

  fi

elif [ a == "string2" ]; then 

  if [3 and 4 were not given]; then 

      echo "Arguments 3 and 4 were not given"
      exit

  fi


fi

getopts
不支持此类验证,因此需要使用
case
语句显式执行这些检查:

case "$a" in
  string1)
    [[ -n $one && -n $two ]] || { echo "Arguments 1 and 2 were not given" >&2; exit 2; }
    ;;
  string2)
    [[ -n $three && -n $four ]] || { echo "Arguments 3 and 4 were not given" >&2; exit 2; }
    ;;
  *)
    echo "Unsupported -a argument: $a" >&2
    exit 2
esac

-n和变量有什么关系?我发现,-nx在x不为null的情况下计算为true。