How to get arguments with flags in Bash

后端 未结 11 2096
余生分开走
余生分开走 2020-12-22 15:56

I know that I can easily get positioned parameters like this in bash:

$0 or $1

I want to be able to use flag options like this to s

11条回答
  •  感情败类
    2020-12-22 16:15

    I had trouble using getopts with multiple flags, so I wrote this code. It uses a modal variable to detect flags, and to use those flags to assign arguments to variables.

    Note that, if a flag shouldn't have an argument, something other than setting CURRENTFLAG can be done.

        for MYFIELD in "$@"; do
    
            CHECKFIRST=`echo $MYFIELD | cut -c1`
    
            if [ "$CHECKFIRST" == "-" ]; then
                mode="flag"
            else
                mode="arg"
            fi
    
            if [ "$mode" == "flag" ]; then
                case $MYFIELD in
                    -a)
                        CURRENTFLAG="VARIABLE_A"
                        ;;
                    -b)
                        CURRENTFLAG="VARIABLE_B"
                        ;;
                    -c)
                        CURRENTFLAG="VARIABLE_C"
                        ;;
                esac
            elif [ "$mode" == "arg" ]; then
                case $CURRENTFLAG in
                    VARIABLE_A)
                        VARIABLE_A="$MYFIELD"
                        ;;
                    VARIABLE_B)
                        VARIABLE_B="$MYFIELD"
                        ;;
                    VARIABLE_C)
                        VARIABLE_C="$MYFIELD"
                        ;;
                esac
            fi
        done
    

提交回复
热议问题