Bash getops option variables are empty

130 Views Asked by At

Just got started with using getops, so this one is most likely a rookie error.

I want to pass 2 options for the user to define; -e (env) and -p (project)

./my-script.sh -e development -p hello-world

Here is my code so far:

while getopts "e:p:" option; do
    case $option in
        e) # declare env
            ENV=$OPTARG
        ;;
        p) # declare project 
            PROJECT=$OPTARG
        ;;
    esac
done

echo "env is $ENV"
echo "project is $PROJECT"

However, when I echo the 2 options, both are empty.

I believe the "e:p:" config is correct, as succeeding with : means a value is required. I've seen some resources online about OPTIND, but couldn't get that to work.

What am I missing to be able to pass the ENV and PROJECT options for usage in the rest of my script? Thank you.

1

There are 1 best solutions below

1
Big Bro On

You need to provide the arguments to getopts, by supplying them in the optstring :
replace getopts "e:p:" option with getopts "e:p: $*" option.