How to create a bash script that takes arguments?

后端 未结 5 1627
一整个雨季
一整个雨季 2021-01-31 10:33

I already know about getopts, and this is fine, but it is annoying that you have to have a flag even for mandatory arguments.

Ideally, I\'d like to be able to have a scr

5条回答
  •  天命终不由人
    2021-01-31 11:37

    Don't use the getopts builtin, use getopt(1) instead. They are (subtly) different and do different things well. For you scenario you could do this:

    #!/bin/bash
    
    eval set -- $(getopt -n $0 -o "-rvxl:" -- "$@")
    
    declare r v x l
    declare -a files
    while [ $# -gt 0 ] ; do
            case "$1" in
                    -r) r=1 ; shift ;;
                    -v) v=1 ; shift ;;
                    -x) x=1 ; shift ;;
                    -l) shift ; l="$1" ; shift ;;
                    --) shift ;;
                    -*) echo "bad option '$1'" ; exit 1 ;;
                    *) files=("${files[@]}" "$1") ; shift ;;
             esac
    done
    
    if [ ${#files} -eq 0 ] ; then
            echo output file required
            exit 1
    fi
    
    [ ! -z "$r" ] && echo "r on"
    [ ! -z "$v" ] && echo "v on"
    [ ! -z "$x" ] && echo "x on"
    
    [ ! -z "$l" ] && echo "l == $l"
    
    echo "output file(s): ${files[@]}"
    

    EDIT: for completeness I have provided an example of handling an option requiring an argument.

提交回复
热议问题