Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash tools for parsing arguments

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.

like image 320
BCS Avatar asked Feb 05 '26 16:02

BCS


1 Answers

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"'
like image 100
R Samuel Klatchko Avatar answered Feb 12 '26 17:02

R Samuel Klatchko