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...

1 Answer 1

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
1
  • 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! Commented Mar 21, 2016 at 16:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.