0

I am writing a script using getopt to parse parameters. The solution I have so far only accepts one parameter. Is there a way to make this solution accept multiple parameters (eg. both '-f and -l)?

solution in link does not work for me. Bash getopt accepting multiple parameters

code: '''

while getopts "f:l:" option; do
      case "${option}" in
          f) firstdate=${OPTARG}
             shift
             ;;
          l) lastdate=${OPTORG}
             ;;
         *)
            echo "UsageInfo"
            exit 1
            ;;
       esac
      shift
    done

'''

NVNK
  • 21
  • 6
  • Remove the `shift`s inside the loop. If you want to remove the option arguments after they've been processed, add `shift $((OPTIND-1))` *after* the end of the loop. – Gordon Davisson Aug 13 '21 at 18:07

1 Answers1

2

First, you have a typo: OPTORG should be OPTARG.

More importantly, you don't need the calls to shift. getopts takes care of consuming and skipping over each option and argument.

while getopts "f:l:" option; do
  case "${option}" in
      f) firstdate=${OPTARG} ;;
      l) lastdate=${OPTARG} ;;
      *)
        echo "UsageInfo"
        exit 1
        ;;
   esac
done
chepner
  • 497,756
  • 71
  • 530
  • 681