sachin sarangamath
sachin sarangamath

Reputation: 455

2 mandatory arguments in getopts in shell script

Execution of shell script which needs 2 mandatory arguments -d and -v and 1 optional argument -h not working accordingly

executing the script store.sh like below

store.sh -d <directory> -v<version>

I tried this like below, but its not working, the script is running with one argument also i.e -d without -v

while getopts "hd:v:" arg; do
  case "$arg" in
    h) usage 0;;
    d) DIRECTORY="$optarg"  ;;
    v) VERSION="$optarg" ;;
    *) usage 1;;
  esac
done  

Upvotes: 1

Views: 251

Answers (1)

Walter A
Walter A

Reputation: 19982

Start the script with setting the DIRECTORY and VERSION to an empty string (better use lowercase for them, directory and version).
After the while loop check the variables:

test -z "${directory}" && usage 1
test -z "${version}" && usage 1

When you want to support empty directory/version, introduce an extra var option_d_given.

Upvotes: 1

Related Questions