Home > Enterprise >  Bash getopts parsing script arguments unexpectedly
Bash getopts parsing script arguments unexpectedly

Time:10-26

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.

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!

CodePudding user response:

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
                  ^--------------
  • Related