Using getopts to process long and short command line options

后端 未结 30 1603
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 22:52

I wish to have long and short forms of command line options invoked using my shell script.

I know that getopts can be used, but like in Perl, I have not

30条回答
  •  忘了有多久
    2020-11-21 23:24

    Here you can find a few different approaches for complex option parsing in bash: http://mywiki.wooledge.org/ComplexOptionParsing

    I did create the following one, and I think it's a good one, because it's minimal code and both long and short options work. A long option can also have multiple arguments with this approach.

    #!/bin/bash
    # Uses bash extensions.  Not portable as written.
    
    declare -A longoptspec
    longoptspec=( [loglevel]=1 ) #use associative array to declare how many arguments a long option expects, in this case we declare that loglevel expects/has one argument, long options that aren't listed i n this way will have zero arguments by default
    optspec=":h-:"
    while getopts "$optspec" opt; do
    while true; do
        case "${opt}" in
            -) #OPTARG is name-of-long-option or name-of-long-option=value
                if [[ "${OPTARG}" =~ .*=.* ]] #with this --key=value format only one argument is possible
                then
                    opt=${OPTARG/=*/}
                    OPTARG=${OPTARG#*=}
                    ((OPTIND--))    
                else #with this --key value1 value2 format multiple arguments are possible
                    opt="$OPTARG"
                    OPTARG=(${@:OPTIND:$((longoptspec[$opt]))})
                fi
                ((OPTIND+=longoptspec[$opt]))
                continue #now that opt/OPTARG are set we can process them as if getopts would've given us long options
                ;;
            loglevel)
              loglevel=$OPTARG
                ;;
            h|help)
                echo "usage: $0 [--loglevel[=]]" >&2
                exit 2
                ;;
        esac
    break; done
    done
    
    # End of file
    

提交回复
热议问题