0

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"

1 Answer 1

4

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
$
Sign up to request clarification or add additional context in comments.

3 Comments

You should probably also edit the usage message to reflect the actual options.
Thank you. I do have a quick question. How can I make this script stop if no arguments are provided.
@maximusdooku Add your check for no arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.