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?
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?
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 $@.
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
A nice example of how to implement short & long switches side by side is mcurl:
http://www.goforlinux.de/scripts/mcurl/
Cheers,
jon