Using getopts to process long and short command line options

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

    If all your long options have unique, and matching, first characters as the short options, so for example

    ./slamm --chaos 23 --plenty test -quiet
    

    Is the same as

    ./slamm -c 23 -p test -q
    

    You can use this before getopts to rewrite $args:

    # change long options to short options
    
    for arg; do 
        [[ "${arg:0:1}" == "-" ]] && delim="" || delim="\""
        if [ "${arg:0:2}" == "--" ]; 
           then args="${args} -${arg:2:1}" 
           else args="${args} ${delim}${arg}${delim}"
        fi
    done
    
    # reset the incoming args
    eval set -- $args
    
    # proceed as usual
    while getopts ":b:la:h" OPTION; do
        .....
    

    Thanks for mtvee for the inspiration ;-)

提交回复
热议问题