如何使用 getopts 在 bash 中获取多个参数?

How can I take multiple arguments in bash using getopts?

我是第一次使用getopts。我正在尝试接受 2 个参数:startyearendyear,脚本将基于这些参数继续进行大量计算。但是我无法完成这项工作。

我得到回显变量的空白。我做错了什么?

!/bin/bash

while getopts 'hse:' OPTION; do
  case "$OPTION" in
    h)
      echo "h stands for h"
      ;;

    s)
      startyear="$OPTARG"
      echo "The value provided is $OPTARG"
      ;;

    e)
      endyear="$OPTARG"
      echo "The value provided is $OPTARG"
      ;;
    ?)
      echo "script usage: $(basename [=11=]) [-l] [-h] [-a somevalue]" >&2
      exit 1
      ;;
  esac
done
shift "$(($OPTIND -1))"

echo "The value provided is $startyear and $endyear"

根据 Gordon Davisson 的建议更新。

您需要在 s 和 e 之后包含“:”,以表示这些选项需要参数。

#!/bin/bash

function help() {
    # print the help to stderr
    echo "$(basename [=10=]) -h -s startyear -e endyear" 2>&1
    exit 1
}

# Stop script if no arguments are present
if (($# == 0))
then
    help
fi

while getopts 'hs:e:' OPTION; do
  case "$OPTION" in
    h)
      help
      ;;
    s)
      startyear="$OPTARG"
      ;;

    e)
      endyear="$OPTARG"
      ;;
  esac
done
shift "$(($OPTIND -1))"

# Checking if the startyear and endyear are 4 digits
if [[ ! ${startyear} =~ ^[0-9]{4,4}$ ]] || [[ ! ${endyear} =~ ^[0-9]{4,4}$ ]]
then
    echo "Error: invalid year" 2>&1
    help
fi

echo "The value provided is $startyear and $endyear"

我的测试 运行 以上。

$ ./geto -s 2018 -e 2020
The value provided is 2018
The value provided is 2020
The value provided is 2018 and 2020
$