Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top