views:

606

answers:

4

I need to write a bash script, and would like it to parse unordered parameters of the format:

scriptname --param1 <string> --param2 <string> --param3 <date>

Is there a simple way to accomplish this, or am I pretty much stuck with $1, $2, $3?

+3  A: 

You want getopts.

Lance Richardson
getopts doesn't support long switches (starting with --). getopt does, but it is pretty horrible to use/read
Cameron
Good point - if long switches are a must-have, getopts isn't the right tool.
Lance Richardson
+1  A: 

Bash has a getops function, as mentioned here before, that might solve your problems.

If you need anything more sophisticated, bash also supports positional parameters (ordered $1 ... $9, and then ${10} .... ${n}), you'll have to come up with your own logic to handle this input. One easy way to go is to put a switch/case inside of a for loop, iterating over the parameters. You can use either one of the two special bash vars that handle the input: $* or $@.

Macalendas
+2  A: 
while [[ $1 = -* ]]; do
    arg=$1; shift           # shift the found arg away.

    case $arg in
        --foo)
            do_foo "$2"
            shift           # foo takes an arg, needs an extra shift
            ;;
        --bar)
            do_bar          # bar takes no arg, doesn't need an extra shift
            ;;
    esac
done
lhunath
+1  A: 

A nice example of how to implement short & long switches side by side is mcurl:

http://www.goforlinux.de/scripts/mcurl/

Cheers,

jon