user182944
user182944

Reputation: 8067

getopts: unable to identify arguments

This is the script I tried:

#!/bin/bash
while getopts ":u:p:" option; do
        case $option in
                u) USER=$OPTARG;;
                p) PASS=$OPTARG;;
                \?) echo "Invalid Option: $OPTARG"
                    exit 1;;
                :) echo "Please provide an argument for $OPTARG!"
                   exit 1;;
        esac
done
echo "Username/Password: $USER/$PASS"

If command for running the script is:

./test9.sh -u test -p -a

Then I am getting an output:

Username/Password: test/-a

-a is an invalid argument but the script is taking -a as password. I would like to display a message Please enter a password and exit the script. Please help me in fixing this.

Upvotes: 0

Views: 179

Answers (2)

carnicer
carnicer

Reputation: 523

I haven't tested your script, but I think that if you use getopt instead of getopts you'll get the result you expect, an error because -a is not a valid option.

Upvotes: 0

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

There are three kinds of parameters: options, option arguments, and positional parameters. If a parameter is an option that requires an argument, then the next parameter will be treated as an an argument no matter what. It may start with a dash or even coincide with a valid option, it will still be treated as an option argument.

If your program wants to reject arguments that start with a dash, you need to program it yourself. Passwords that start with a dash are perfectly legitimate; a program that checks passwords must not reject them.

Option that accept optional arguments are extremely confusing and non-standard. Getopt in general doesn't support them. There's a GNU extension for that, but don't use it.

TL;DR there's nothing to fix, your script is fine.

Upvotes: 1

Related Questions