1

I'm trying to figure out a way to deny the usage of more than one getopts args in a certain situation. Say we have something like this:

while getopts "a:b:c:def" variable; do
case $variable in
a)a=$OPTARG
b)b=$OPTARG
c)c=$OPTARG
d)MODE=SMTH
e)MODE=SMTH2
f)MODE=SMTH3
esac
done

What im trying to do is to deny the use of more than one MODE arg (def) and display a message to tell that to the user. Something in the line of:

./script.sh -a ajhsd -b kjdhas -c daskjdha -d -e -f

performs check for use of more than one MODE arg(def) and if more than one is used displays an error message. I tried with a simple input check if statement but failed miserably. It always passes through all three and obtains the last passed argument parameter without even going inside the multiple args check. Kind of weird. It should've been easy to do this. Should have...

4

You need to initialize MODE as some value other than SMTH, SMTH2 and SMTH3. Then, check if MODE is at the initial value. If not, throw an error message and then exit. You have to exit after error, otherwise script will keep running. The modified version of your script below should get you started.

MODE=0
EMSG="More than one of -d, -e, -f has been specified"
while getopts "a:b:c:def" variable; do
case $variable in
a) a=$OPTARG ;;
b) b=$OPTARG ;;
c) c=$OPTARG ;;
d) if [ $MODE = 0 ] ; then MODE=SMTH  ; else  echo $EMSG  ; exit 1 ; fi ;;
e) if [ $MODE = 0 ] ; then MODE=SMTH2 ; else  echo $EMSG  ; exit 1 ; fi ;;
f) if [ $MODE = 0 ] ; then MODE=SMTH3 ; else  echo $EMSG  ; exit 1 ; fi ;;
esac
done
  • this is as good as it gets. i was trying to do something way more complex, but never thought of doing the check in the field of each of the options. this is great! – Nikolai Uzunov Mar 21 '16 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.