Validating command line arguments with GetOpts and required parameters

I am creating a basic script that should accept 3 required command line parameters, and each should be followed by a value. Like this:

$ myscript.sh -u <username> -p <password> -f <hosts.txt> 

I try to make sure that the user passes these exact 3 options and their values, and nothing else, otherwise I want to print a usage message and exit.

I read on getopts and came up with this:

 usage () { echo "Usage : $0 -u <username> -p <password> -f <hostsFile>"; } if [ $# -ne 6 ] then usage exit 1 fi while getopts u:p:f: opt ; do case $opt in u) USER_NAME=$OPTARG ;; p) USER_PASSWORD=$OPTARG ;; f) HOSTS_FILE=$OPTARG ;; *) usage; exit 1;; esac done echo "USERNAME: $USER_NAME" echo "PASS: $USER_PASSWORD" echo "FILE: $HOSTS_FILE" 

I was hoping that if I did not pass on any of my 3 โ€œrequiredโ€ options (for example, -u -p -f), Optargs validation could be taken with the case of โ€œ *) โ€. Although this is true for other options, such as "-a", "-b", etc., in this particular case it does not look like:

 $ myscript.sh 1 2 3 4 5 6 

Getops does not consider this as invalid input, but the script is moved when executing echo commands containing 3 empty variables.

How can I capture the above as invalid because it is not in form:

 $ myscript.sh -u <username> -p <password> -f <hosts.txt> 

Thanks!

+5
source share
1 answer

getopts has no concept of "required" options. The colon in u:p:f: means that if one of these parameters is provided, then the argument for this parameter is required. However, a pair of argument options is always optional.

You can require the user to provide all three, but with code, for example:

 if [ ! "$USER_NAME" ] || [ ! "$USER_PASSWORD" ] || [ ! "$HOSTS_FILE" ] then usage exit 1 fi 

Put this code after the while getopts .

Role *)

I was hoping that if I didn't pass on any of my 3 โ€œrequiredโ€ options (for example, -u -p -f), Optargs validation could get this through the case of โ€œ*โ€.

Case *) is only executed if an option other than -u , -p or -f . Thus, if someone provided, for example, the -z argument, then this case will work.

+9
source

All Articles