yntnm
yntnm

Reputation: 449

bash - getopts in switch case

I'm trying to use getopts inside a switch case loop. if i use only getopts or only the switch case it's work, however when i combine those two the getopts dos not trigger.

i have search a lot but i cat fins any mention for how to combine them, and problem i missing something stupid so for give me ...

here is the code essence.

#!/bin/bash
case $1 in

        ver)
            echo "vesion"
            exit 0
        ;;
        op)
           while getopts ":a" opt; do
                case $opt in
                 a)
                   echo "-a was triggered!" >&2
                 ;;
                \?)
                   echo "Invalid option: -$OPTARG" >&2
                 ;;
                esac
        done
        ;;
esac

when i do that

# bash -x test.sh op -a

i get

+ case $1 in
+ getopts :a opt

(and without debug i get nothing)

what is that that i missing to combine these two

Thanks :)

Upvotes: 1

Views: 1109

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 29220

You should add a shift instruction at the beginning of your op) choice, before the call to getopts, to eat the op argument itself. Else, the first argument that getopts will analyze is op and it will silently stop (end of options).

Upvotes: 2

Related Questions