Using getopts to process long and short command line options

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

    if simply this is how you want to call the script

    myscript.sh --input1 "ABC" --input2 "PQR" --input2 "XYZ"
    

    then you can follow this simplest way to achieve it 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
    

提交回复
热议问题