bash - switch case 中的 getopts

bash - getopts in switch case

我正在尝试在 switch case 循环中使用 getopts。 如果我只使用 getopts 或只使用 switch case 它是有效的,但是当我将这两个结合使用时,getopts 不会触发。

我搜索了很多,但我发现任何关于如何组合它们的提及,问题是我遗漏了一些愚蠢的东西所以给我...

这里是代码精华。

#!/bin/bash
case  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

当我这样做时

# bash -x test.sh op -a

我得到

+ case  in
+ getopts :a opt

(没有调试我什么也得不到)

我想把这两者结合起来的是什么

谢谢 :)

您应该在 op) 选择的开头添加一条 shift 指令,在调用 getopts 之前,以吃掉 op 参数本身。否则,getopts 将分析的第一个参数是 op,它将静默停止(选项结束)。