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!
source share