Using getopts to process long and short command line options

后端 未结 30 1576
佛祖请我去吃肉
佛祖请我去吃肉 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:07

    The accepted answer does a very nice job of pointing out all the shortcomings of bash built-in getopts. The answer ends with:

    So while it is possible to write more code to work around the lack of support for long options, this is a lot more work and partially defeats the purpose of using a getopt parser to simplify your code.

    And even though I agree in principle with that statement, I feel that the number of times we all implemented this feature in various scripts justifies putting a bit of effort into creating a "standardised", well tested solution.

    As such, I've "upgraded" bash built in getopts by implementing getopts_long in pure bash, with no external dependencies. The usage of the function is 100% compatible with the built-in getopts.

    By including getopts_long (which is hosted on GitHub) in a script, the answer to the original question can be implemented as simply as:

    source "${PATH_TO}/getopts_long.bash"
    
    while getopts_long ':c: copyfile:' OPTKEY; do
        case ${OPTKEY} in
            'c'|'copyfile')
                echo 'file supplied -- ${OPTARG}'
                ;;
            '?')
                echo "INVALID OPTION -- ${OPTARG}" >&2
                exit 1
                ;;
            ':')
                echo "MISSING ARGUMENT for option -- ${OPTARG}" >&2
                exit 1
                ;;
            *)
                echo "Misconfigured OPTSPEC or uncaught option -- ${OPTKEY}" >&2
                exit 1
                ;;
        esac
    done
    
    shift $(( OPTIND - 1 ))
    [[ "${1}" == "--" ]] && shift
    

提交回复
热议问题