bash argument case for args in $@

后端 未结 5 1682
无人共我
无人共我 2021-02-02 12:14

I have a script with a long list of OPTIONAL arguments. some have associated values.

Such as:

.script --first 2012-12-25 --last 2012-12-26 --copy --remov         


        
5条回答
  •  失恋的感觉
    2021-02-02 12:30

    You can allow both --a=arg or -a arg options with a little more work:

    START_DATE="$(date '+%Y-%m-%d')";
    LAST_DATE="$(date '+%Y-%m-%d')";
    while [[ $# -gt 0 ]] && [[ "$1" == "--"* ]] ;
    do
        opt="$1";
        shift;              #expose next argument
        case "$opt" in
            "--" ) break 2;;
            "--first" )
               START_DATE="$1"; shift;;
            "--first="* )     # alternate format: --first=date
               START_DATE="${opt#*=}";;
            "--last" )
               LAST_DATE="$1"; shift;;
            "--last="* )
               LAST_DATE="${opt#*=}";;
            "--copy" )
               COPY=true;;
            "--remove" )
               REMOVE=true;;
            "--optional" )
               OPTIONAL="$optional_default";;     #set to some default value
            "--optional=*" )
               OPTIONAL="${opt#*=}";;             #take argument
            *) echo >&2 "Invalid option: $@"; exit 1;;
       esac
    done
    

    Note the --optional argument uses a default value if "=" is not used, else it sets the value in the normal way.

提交回复
热议问题