JasonGenX
JasonGenX

Reputation: 5434

bash script: how to test for parameter pairs?

I have a bash script with command line params that may look like this:

./myscript.sh -P1 valueofP1 -A3 valueofA3

is there any common method of getting the values shown here and having local script variables P1 and A3 get the value that follows in the next parameter?

Upvotes: 0

Views: 806

Answers (1)

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

shift

while [ $# -gt 0 ]
do
    case $1 in
    -P1)
        shift
        arg=$1
        shift
        echo "P1:$arg"
        ;;
    -A3)
        shift
        arg1=$1
        shift
        arg2=$1
        shift
        echo "A3: $arg1 and $arg2"
        ;;
    *)
        echo "Unknown argument $1" >&2
        exit 1
        ;;
    esac
done

usage:

$ ./test.sh -P1 AAA -A3 B C
P1:AAA
A3: B and C

Upvotes: 1

Related Questions