devinbost
devinbost

Reputation: 5084

Bash parameters not detected

When I attempt to execute my bash script like this:

bin/provision-pulsar-commands -t development -n provisioning

the outputs print:

TENANT =

NAMESPACE =

Here is my script (provision-pulsar-commands):

#!/bin/bash


function display_usage {
    echo "You may override the namespace and tenant for all components for testing, if desired."
    echo "usage: bin/provision-pulsar-commands [-t tenant] [-n namespace]"
    echo "  -t      Override tenant (e.g. development) for all components"
    echo "  -n      Override namespace (e.g. provisioning) for all components"
    echo "  -h      display help"
    exit 1
    }

# check whether user had supplied -h or --help . If yes display usage
    if [[ ( $# == "--help") ||  $# == "-h" ]]
    then
        display_usage
        exit 0
    fi

while getopts tn option
do
case "${option}"
in
t) TENANT=${OPTARG};;
n) NAMESPACE=${OPTARG};;
esac
done

echo "TENANT = $TENANT"
echo "NAMESPACE = $NAMESPACE"

Why are my parameter values not getting picked up? I'm basing my code on these examples:

Clarification: My parameter values are optional. Also, when I pass -h or --help, my display_usage function is not called. It's not clear to me if that's related to the problem or not.

Upvotes: 2

Views: 627

Answers (2)

chepner
chepner

Reputation: 531918

You have to tell getopts that -t and -n take arguments.

while getopts t:n: option; do

Without the colons, -t is recognized as an option, but OPTARG isn't set. The next argument (development) is neither -t nor -n, so terminates the loop.

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361919

Add : to options that take arguments.

getopts t:n: option

Upvotes: 0

Related Questions