Using getopts to process long and short command line options

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

    I don't have enough rep yet to comment or vote his solution up, but sme's answer worked extremely well for me. The only issue I ran into was that the arguments end up wrapped in single-quotes (so I have an strip them out).

    I also added some example usages and HELP text. I'll included my slightly extended version here:

    #!/bin/bash
    
    # getopt example
    # from: https://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options
    HELP_TEXT=\
    "   USAGE:\n
        Accepts - and -- flags, can specify options that require a value, and can be in any order. A double-hyphen (--) will stop processing options.\n\n
    
        Accepts the following forms:\n\n
    
        getopt-example.sh -a -b -c value-for-c some-arg\n
        getopt-example.sh -c value-for-c -a -b some-arg\n
        getopt-example.sh -abc some-arg\n
        getopt-example.sh --along --blong --clong value-for-c -a -b -c some-arg\n
        getopt-example.sh some-arg --clong value-for-c\n
        getopt-example.sh
    "
    
    aflag=false
    bflag=false
    cargument=""
    
    # options may be followed by one colon to indicate they have a required argument
    if ! options=$(getopt -o abc:h\? -l along,blong,help,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=true ;;
        -b|--blong) bflag=true ;;
        # for options with required arguments, an additional shift is required
        -c|--clong) cargument="$2" ; shift;;
        -h|--help|-\?) echo -e $HELP_TEXT; exit;;
        (--) shift; break;;
        (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
        (*) break;;
        esac
        shift
    done
    
    # to remove the single quotes around arguments, pipe the output into:
    # | sed -e "s/^'\\|'$//g"  (just leading/trailing) or | sed -e "s/'//g"  (all)
    
    echo aflag=${aflag}
    echo bflag=${bflag}
    echo cargument=${cargument}
    
    while [ $# -gt 0 ]
    do
        echo arg=$1
        shift
    
        if [[ $aflag == true ]]; then
            echo a is true
        fi
    
    done
    

提交回复
热议问题