How can I use long options with the Bash getopts builtin?

前端 未结 9 1173
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 11:25

I am trying to parse a -temp option with Bash getopts. I\'m calling my script like this:

./myscript -temp /foo/bar/someFile

He

相关标签:
9条回答
  • 2020-12-24 11:52

    the simplest way to achieve this is with the help of getopt and --longoptions

    try this , hope this is useful

    # Read command line options
    ARGUMENT_LIST=(
        "input1"
        "input2"
        "input3"
    )
    
    
    
    # read arguments
    opts=$(getopt \
        --longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
        --name "$(basename "$0")" \
        --options "" \
        -- "$@"
    )
    
    
    echo $opts
    
    eval set --$opts
    
    while true; do
        case "$1" in
        --input1)  
            shift
            empId=$1
            ;;
        --input2)  
            shift
            fromDate=$1
            ;;
        --input3)  
            shift
            toDate=$1
            ;;
          --)
            shift
            break
            ;;
        esac
        shift
    done
    

    and this is how - you call the shell script

    myscript.sh --input1 "ABC" --input2 "PQR" --input2 "XYZ"
    
    0 讨论(0)
  • 2020-12-24 11:53

    getopts can only parse short options.

    Most systems also have an external getopt command, but getopt is not standard, and is generally broken by design as it can't handle all arguments safely (arguments with whitespace and empty arguments), only GNU getopt can handle them safely, but only if you use it in a GNU-specific way.

    The easier choice is to use neither, just iterate the script's arguments with a while-loop and do the parsing yourself.

    See http://mywiki.wooledge.org/BashFAQ/035 for an example.

    0 讨论(0)
  • 2020-12-24 11:53

    getopts is used by shell procedures to parse positional parameters of 1 character only (no GNU-style long options (--myoption) or XF86-style long options (-myoption))

    0 讨论(0)
提交回复
热议问题