Using getopts to process long and short command line options

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

    getopts "could be used" for parsing long options as long as you don't expect them to have arguments...

    Here's how to:

    $ cat > longopt
    while getopts 'e:-:' OPT; do
      case $OPT in
        e) echo echo: $OPTARG;;
        -) #long option
           case $OPTARG in
             long-option) echo long option;;
             *) echo long option: $OPTARG;;
           esac;;
      esac
    done
    
    $ bash longopt -e asd --long-option --long1 --long2 -e test
    echo: asd
    long option
    long option: long1
    long option: long2
    echo: test
    

    If you try to use OPTIND for getting a parameter for the long option, getopts will treat it as the first no optional positional parameter and will stop parsing any other parameters. In such a case you'll be better off handling it manually with a simple case statement.

    This will "always" work:

    $ cat >longopt2
    while (($#)); do
        OPT=$1
        shift
        case $OPT in
            --*) case ${OPT:2} in
                long1) echo long1 option;;
                complex) echo comples with argument $1; shift;;
            esac;;
    
            -*) case ${OPT:1} in
                a) echo short option a;;
                b) echo short option b with parameter $1; shift;;
            esac;;
        esac
    done
    
    
    $ bash longopt2 --complex abc -a --long -b test
    comples with argument abc
    short option a
    short option b with parameter test
    

    Albeit is not as flexible as getopts and you have to do much of the error checking code yourself within the case instances...

    But it is an option.

提交回复
热议问题