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.

BCS
  • 75,627
  • 68
  • 187
  • 294
  • getopts is the best I have found to date. It's a little idiosyncratic but works well for my needs. – Eric J. May 17 '10 at 17:41
  • 1
    did you check http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options ? looks similar to what you need – bobah May 17 '10 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. – BCS May 17 '10 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)`](http://linux.die.net/man/1/getopt) (long and short options). [This page](http://mywiki.wooledge.org/BashFAQ/035) recommends avoiding the latter. – Dennis Williamson May 17 '10 at 19:11

1 Answers1

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"'
BCS
  • 75,627
  • 68
  • 187
  • 294
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187