views:

311

answers:

2

I need to be able to read list of variables that follow certain parameter(similar to say mysqldump --databases db1 db2 db3)

Basically script should be invoked like this:

./charge.sh --notify --target aig wfc msft --amount 1bln

In the script itself I need to assign "aig wfc msft" either to a single variable or create an array out of them.

What would be a good way of doing that?

+2  A: 

If you can invoke the script like this (note the quotes):

./charge.sh --notify --target "aig wfc msft" --amount 1bln

You can assign "aig wcf msft" to a single variable.

If you cannot change the way the script is invoked and if you can guarantee that the --target option arguments are always followed by another option or other delimiter, you could grab the arguments between them and store them in a variable.

var=$(echo $* | sed -e 's/.*--target\(.*\)--.*/\1/')
jschmier
+2  A: 

I often find the shift statement to be really useful in situations like this. In a while loop, you can test for expected options in a case statement, popping argument 0 off during every iteration with shift, until you either get to the end, or the first positional parameter.

When you get to the --target argument in the loop, you can use shift, to pop it off the argument list, then in a loop, append each argument to a list (in this case $TARGET_LIST) and shift, until you get to the end of the argument list, or the next option (when '$1' starts with '-').

NOTIFY=0
AMOUNT=''
TARGET_LIST=''

while :; do
    case "$1" in
        -h|--help)
            echo "$HELP"
            exit 0
            ;;
        --notify)
            NOTIFY=1
            shift
            ;;
        --amount)
            shift; AMOUNT="$1"; shift
            ;;
        --target)
            shift
            while ! echo "$1" | egrep '^-' > /dev/null 2>&1 && [ ! -z "$1" ]; do
                TARGET_LIST="$TARGET_LIST $1"
                shift
            done
            ;;
        -*)
            # Unexpected option
            echo $USAGE
            exit 2
            ;;
        *)
            break
            ;;
    esac
done
Kyle Ambroff