0

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!

1 Answer 1

2

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

1 Comment

@hotmeatballsoup, additionally it's good practice to remove the options from the positional paremeters after you've processed them: after the while loop add: shift $((OPTIND - 1))

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.