Bash – Pass a list of variables to a Bash script

bashcommand-linescripting

I need to be able to read a list of variables that follow certain parameters (similar to, say, mysqldump –databases db1 db2 db3)

Basically the 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?

Best Solution

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