1

I am not good at Bash scripting, and trying to learn more. Let me introduce my question with code:

#!/bin/bash
version_num=
isWindows=
MSVC_VER=
VERBOSE=
while getopts “hw:v:m:V” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         w)
             isWindows=$OPTARG
             ;;
         v)
             version_num=$OPTARG
             ;;
         m)
             MSVC_VER=$OPTARG
             ;;
         V)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

For space, usage function is removed.

My questions are:

First question:

currently, if I use this script, I have to feed parameter values after each option, for example:

 `bash test_bash.sh -v 4.2.2.0 -m 10.0 -w 1`

However, assuming that I only need to see whether -w is present, then set some variable value. I don't want to provide -w 1 since 1 is just a flag to do something. I would like the script to work like:

 bash test_bash.sh -w -v 4.2.2.0 -m 10.0

How can I achieve this? I would like to do something like rm -r -f, which can have multiple options and does not require that each option is followed by some value.

Second question:

if I remove

V)
   VERBOSE=1 
   ;;

and :V from the while line as well as VERBOSE=, this script does not work anymore. Is it because :V is required?

Thanks a lot for your time and help!

1 Answer 1

4

Putting a : after a letter in the getopts parameter indicates whether it takes a parameter after it or not. So change to:

while getopts “hwv:m:V” OPTION

Removeing :V from the script breaks it because the : is for the m option that comes before it, not the V option that comes after. When you remove that :, it means that m no longer takes a parameter, but you need that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.