getopt - 如何避免读取下一个标志作为参数?

getopt - 如何避免读取下一个标志作为参数?

当我使用 getopt 并通过空参数传递所需的标志时,它会读取下一个标志作为参数。需要帮助添加某种检查来区分包含破折号 (-) 和双精度 (--) 的标志,否则将其识别为错误,然后调用Usage 函数。

./test.sh -s -h

输出:

 -s '-h' --

DBSTORE=-h
DBHOST=

这是我正在处理的代码:

#!/bin/bash

################################################
# Usage function display how to run the script #
################################################
function usage(){
    cat << EOF
    Usage: ./test.sh [-s] <abc|def|ghi> [-h] <Hostname>

    This script does foo.
    OPTIONS:
        -H | --help         Display help options
        -s | --store STORE  OpenDJ Store type [abc|def|ghi]
        -h | --Host  HOST   Hostname of the servers
EOF
}

##########################################
# Parse short/long options with 'getopt' #
##########################################
function getOpts(){
    # Option strings:
    SHORT=s:h:H
    LONG=store:,host:,help
    # Read the options
    OPTS=$(getopt --options $SHORT --long $LONG --name "$0" -- "$@")

    if [ $? != 0 ]; then
        echo "Failed to parse options...!" >&2
        usage
        echo ""
        exit 1
    fi
    echo "$OPTS"
    eval set -- "$OPTS"

    # Set initial values:
    DBSTORE=
    DBHOST=
    HELP=false

    # Extract options and their arguments into variables:
    NOARG="true"
    while true; do
        case "$1" in
            -s | --store )
                            DBSTORE=$2;
                            shift 2
                            ;;
            -h | --host )
                            DBHOST="$2"
                            shift 2
                            ;;
            -H | --help )
                            usage
                            echo ""
                            shift
                            shift
                            exit 1
                            ;;
            -- )
                    shift
                    break
                    ;;
            \?)
                echo -e "Invalid option: -$OPTARG\n" >&2
                usage;
                echo ""
                exit 1
                ;;
            :) 
                echo -e "Missing argument for -$OPTARG\n" >&2
                usage;
                echo ""
                exit 1
                ;;
            *) 
                echo -e "Unimplemented option: -$OPTARG\n" >&2
                usage;
                echo ""
                exit 1
                ;;
      esac
      NOARG="false"
    done
    [[ "$NOARG" == "true" ]] && { echo "No argument was passed...!"; usage; echo ""; exit 1; }
}

getOpts "${@}"

echo DBSTORE=$DBSTORE
echo DBHOST=$DBHOST

exit 0

相关内容