3

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.

4
  • getopts is the best I have found to date. It's a little idiosyncratic but works well for my needs. Commented May 17, 2010 at 17:41
  • 1
    did you check stackoverflow.com/questions/402377/… ? looks similar to what you need Commented May 17, 2010 at 17:42
  • @bobah: Very related, and in fact might be a building block to what I'm looking for, but I'm looking for something a bit more specialized. Also, I'm looking for a cut-n-paste solution as what I've got is good enough for now. Commented May 17, 2010 at 17:52
  • 1
    Make sure you're aware of the difference between the Bash builtin getopts (short options only) and the external executable getopt(1) (long and short options). This page recommends avoiding the latter. Commented May 17, 2010 at 19:11

1 Answer 1

1

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"'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.