Using getopts to process long and short command line options

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

    Here's an example that actually uses getopt with long options:

    aflag=no
    bflag=no
    cargument=none
    
    # options may be followed by one colon to indicate they have a required argument
    if ! options=$(getopt -o abc: -l along,blong,clong: -- "$@")
    then
        # something went wrong, getopt will put out an error message for us
        exit 1
    fi
    
    set -- $options
    
    while [ $# -gt 0 ]
    do
        case $1 in
        -a|--along) aflag="yes" ;;
        -b|--blong) bflag="yes" ;;
        # for options with required arguments, an additional shift is required
        -c|--clong) cargument="$2" ; shift;;
        (--) shift; break;;
        (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
        (*) break;;
        esac
        shift
    done
    

提交回复
热议问题