문제

I've the following script:

#!/bin/bash

USER="NONE"
LOST=0
AVG=0

while getopts ":pmu:" OPTION; do
    case $OPTION in
        u)
            USER=$OPTARG
            ;;
        p)
            LOST=1
            ;;
        m)
            AVG=1
            ;;
        \?)
            echo "Invalid argument: -$OPTARG"
            exit 1
            ;;
        :)
            echo "-$OPTARG requires an argument."
            exit 1
            ;;
    esac
done

echo "$USER-$LOST-$AVG"

exit 0

I want the -u option to take an argument. The script correctly recognizes invalid options and when -u is called without an argument. But unfortunately, when I type:

myscript -u -m -p

It prints:

-m-1-0

So, it uses -m as -u argument and ignores the -m option itself.

도움이 되었습니까?

해결책

You told getopts that the -u option was followed by an option-argument. -m is a string value; the fact that it starts with a - sign is immaterial to its status as an option-argument; you are allowed to use - at the start of an option-argument value.

So, your observations are correct. That is the intended design; this is the way the getopt() function works, and it is an implementation of the POSIX Utility Syntax Guidelines — a slightly relaxed version of those guidelines, in fact. If you don't like it, use something else other than getopts, but you'll be fighting against the system.

Note that although POSIX getopt() allows 'optional option-arguments' in theory, in practice, only the last option on the command line can have an optional option-argument, making them essentially useless.

It is perfectly possible to devise option parsing systems that behave differently and which substantially satisfy the Utility Syntax Guidelines; many people have done it. Indeed, the GNU getopt program is an extended implementation which is likely what you should be looking at — but it has a very different invocation to get to the behaviour (see also Using getopts in bash shell script to get long and short command line options). The systems are all different, and it is usually complex to describe the required option handling behaviour succinctly yet unambiguously. See Solaris CLIP — Command Line Interface Paradigm for more information*.

* Google search term 'solaris clip' gets you movie clips for the movie 'Solaris'. A working search term is 'Solaris command line interface paradigm'.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top