首页 > 解决方案 > 用于参数检查的 getopts bash 查询

问题描述

我有一个如下的 getops 脚本..我遇到了这个脚本的问题..用法是

Usage: ./getoptstest.sh [-f] [ -i INSTANCES ]

如果我通过了,./getoptstest.sh -f -i 1.2.3.4 ,结果效果很好,

Result
    f good
    i good
    1.2.3.4
    No args

但是如果我切换选项, ./getoptstest.sh -i -f ,它会将“-f”作为“-i”的参数。

Result:
    i good
    -f -->This is the result of echo statement printing the argument for -i.
    No args

我希望脚本严格检查 -i 参数,而不是将 -f 作为其参数。-f 本身就是一个不同的选项。请帮我修改什么来实现这一点。

这是我的脚本..

while getopts ":hfi:" opt; do
    case $opt in
        i)  INSTANCES="$OPTARG"
            echo "i good"
            echo $INSTANCES
            ;;
        f)  FORCE=1
            echo "f good"
            ;;
        h)  usage
            exit;;
        \?) echo "Usage: Invalid option: -$OPTARG" >&2
            ;;
        :)  echo "Option -$OPTARG requires an argument." >&2
            exit 1
            ;;
        *)  usage 
            exit;;
    esac
done

标签: bashgetopts

解决方案


推荐阅读