Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash getopts parsing script arguments unexpectedly

I have the following bash script:

#!/bin/bash
function usage() {
  printf "\n"
  echo "Updates a Lambda with env vars stored in a Secrets Manager secret. Complete drop n' swap."
  printf "\n"
  echo "Syntax: bash $0 -a <ARN> -s <secretName> [-h]"
  echo "options:"
  echo "a       the ARN of the Lambda to update"
  echo "s       the name of the secret in Secrets Manager to use"
  echo "h       display help"
  printf "\n"
  exit
}

while getopts ":has:" option; do
  case $option in
    h) # display help
      usage
      ;;
    a) # ARN of the lambda
      arn=${OPTARG}
      [[ -z "$arn" ]] && usage
      ;;
    s) # Secrets Manager secret (name)
      secretName=${OPTARG}
      [[ -z "$secretName" ]] && usage
      ;;
    *) # catchall
      usage
  esac
done

echo "all good! arn = $arn and secret = $secretName"

When I run this I get:

myuser@mymachine myapp % bash myscript.sh -a abba -s babba

Updates a Lambda with env vars stored in a Secrets Manager secret. Complete drop n' swap.

Syntax: bash myscript.sh -a <ARN> -s <secretName> [-h]
options:
a       the ARN of the Lambda to update
s       the name of the secret in Secrets Manager to use
h       display help

I was expecting all of the arguments (parsed by getopts) to be valid and to see the "all good!..." output instead of the usage output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Where am I going awry? Am I using/parsing getopts incorrectly, or am I invoking the script with argument incorrectly? Or both?! Thanks in advance!

>Solution :

Since -a is supposed to have an associated value you want to append a : to the a option, ie:

# change this:

while getopts ":has:" option

# to this:

while getopts ":ha:s:" option
                  ^--------------
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading