maximusdooku
maximusdooku

Reputation: 5512

How can I take multiple arguments in bash using getopts?

I am using getopts for the first time. And I am trying to accept 2 arguments: startyear and endyear, based on which the script will continue doing a lot of calculations. But I am not able to make this work.

I am getting blanks for echo variables. What am I doing wrong?

!/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"

Upvotes: 0

Views: 583

Answers (1)

WaltDe
WaltDe

Reputation: 1832

Updated at suggestion of Gordon Davisson.

You need to include the ':' after both the s and e to signal that those options are expecting arguments.

#!/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"

My test run with the above.

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

Upvotes: 4

Related Questions