문제

I am trying to parse two options which both need an argument.

#!/bin/bash

while getopts "a:b:" opt; do
    case $opt in
    a)
        echo "a has the argument $OPTARG."
        shift
        ;;
    b)
        echo "b has the argument $OPTARG."
        shift
        ;;
    esac
done

What I expect is that this script prints out the arguments of a and b. But the output is only:

$ sh ./cmd_parse_test.sh -a foo -b bar
a has the argument foo.

What am I doing wrong?

도움이 되었습니까?

해결책

You don't have to shift to get the next argument. Simply dump whatever you want, and continue for the next iteration, as in:

#!/bin/bash

while getopts "a:b:" opt; do
    case $opt in
    a)
        echo "a has the argument $OPTARG."
        ;;
    b)
        echo "b has the argument $OPTARG."
        ;;
    esac
done

Which outputs:

$ ./cmd_parse_test.sh -a foo -b bar
a has the argument foo.
b has the argument bar.

Notice also that you don't have to run the script with sh, since you've already set the shbang to use bash.

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