getopts to use for both flags and option parsing

2019-08-15 01:14发布

问题:

I am using getopts in my script and I want to work it for all the following order of option parsing.

./myscript -c server
./myscript -c -h server
./myscript server -c
./myscript -h server -c
./myscript server

I am using myscript as follows.

#!/bin/bash
while getopts c:h: var
do
case $var in 
h) host=$OPTARG;;
c) FLAG=1
esac
done

Here "server" is a argument and should load even -h option specifies or not and also -c option I am using for a FLAG.Is there a way to get this achieved.

回答1:

Sometimes it's better not to use getopts at all:

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -c)
        FLAG=1
        ;;
    -h)
        HOST=$2
        shift
        ;;
    -*)
        echo "Unknown option: $1"
        exit 1
        ;;
    *)
        HOST=$1
        ;;
    esac
    shift
done

By the way your script would give you a syntax error since you missed the two semicolons:

c) FLAG=1 ;;


回答2:

I fixed my issue by applying some extra validations..

#!/bin/bash

USAGE() {
        echo "Invalid Option"
        exit 1
}

if [ $# -eq 2 ]; then
                case $1 in
                        -c) FLAG=1; host=$2 ;;
                        -h) host=$2 ;;
                esac
                if [ -z "$host" ]; then
                case $2 in
                        -c) FLAG=1; host=$1;;
                        -h) host=$1;;
                        *) USAGE;;
                esac
                fi
        else

        while getopts q:c:h: OPTION
        do
            case ${OPTION} in
                q) USAGE;;
                h) host=$OPTARG;;
                c) FLAG=1 ;;
                *)USAGE;;
            esac
        done
fi

if [ $# -eq 1 ]; then host=$1 ;fi

echo Host = $host FLag = $FLAG

In all the cases I am getting my host in my script as shown in this output.

$ ./myscript.sh server1
Host = server1 FLag =
$ ./myscript.sh -c server1
Host = server1 FLag = 1
$ ./myscript.sh server1 -c
Host = server1 FLag = 1
$ ./myscript.sh server1 -h
Host = server1 FLag =
$ ./myscript.sh -h server1
Host = server1 FLag =