Using getopts to process long and short command line options

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

    Another way...

    # translate long options to short
    for arg
    do
        delim=""
        case "$arg" in
           --help) args="${args}-h ";;
           --verbose) args="${args}-v ";;
           --config) args="${args}-c ";;
           # pass through anything else
           *) [[ "${arg:0:1}" == "-" ]] || delim="\""
               args="${args}${delim}${arg}${delim} ";;
        esac
    done
    # reset the translated args
    eval set -- $args
    # now we can process with getopt
    while getopts ":hvc:" opt; do
        case $opt in
            h)  usage ;;
            v)  VERBOSE=true ;;
            c)  source $OPTARG ;;
            \?) usage ;;
            :)
            echo "option -$OPTARG requires an argument"
            usage
            ;;
        esac
    done
    

提交回复
热议问题