views:

72

answers:

1

I have a bash script that uses a few variables (call them $foo and $bar). Right now the script defines them at the top with hard coded values like this:

foo=fooDefault
bar=barDefault

....

# use $foo and $bar

What I want is to be able to use the script like any of these:

myscript              # use all defaults
myscript -foo=altFoo  # use default bar
myscript -bar=altBar  # use default foo
myscript -bar=altBar -foo=altFoo

An ideal solution would allow me to just list the variable that I want to check for flags for.

Is there a reasonably nice way to do this?


I've seen getopt and I think it might do about 70% of what I'm looking for but I'm wondering if there is a tool or indium that builds on it or the like that gets the rest.

+1  A: 

You can use eval to do something close:

foo=fooDefault
bar=barDefault

for arg in "$@"; do
    eval ${arg}
done

This version doesn't bother with a leading dash, so you would run it as:

myscript foo=newvalue

That said, a couple of words of caution. Because we are using eval, the caller can inject any code/data they want into your script. If you need your code to be secure, you are going to have to validate ${arg} before you eval it.

Also, this is not very elegant if you need to have spaces in your data as you will have to double quote them (once for the command line and a second time for the inner eval):

myscript foo='"with sapces"'
R Samuel Klatchko
A little fun with grep/sed might do the trick...
BCS