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

时间:2019-08-15 23:33:31

标签: bash 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 $0) [-l] [-h] [-a somevalue]" >&2
      exit 1
      ;;
  esac
done
shift "$(($OPTIND -1))"

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

1 个答案:

答案 0 :(得分:3)

根据Gordon Davisson的建议进行更新。

您需要在s和e后面都包含':',以表明这些选项需要参数。

#!/bin/bash

function help() {
    # print the help to stderr
    echo "$(basename $0) -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
$