0

I am writing a bash script foo.sh that runs too commands bar with first input argument, and baz with the second argument:

#! /bin/bash
bar "$1"
baz "$2"

Now I want to make foo.sh more flexible, having optional number of arguments for bar and baz, something like the below:

./foo.sh bar_args="-x -v message=hello" baz_args="-d -m"

And I want foo.sh to pass bar_args as the input arguments to bar, and baz_args to baz. I want also foo.sh to work normally if either of the arguments were not given (for instance if bar_args is not provided, bar should be called without any arguments).

How to do this?

  • I would recommend examining a solution like getopt(s) as described in this detailed answer. Getopt(s) in C possesses the ability to do exactly what you want, so I assume you should be able to reproduce that behaviour in Bash. Unfortunately, I've only the time to offer you a pointer and cannot walk you through the details of an implementation (as much as I'd like!) – afeique Oct 23 '14 at 16:08
  • Thanks, I am looking for a bash script solution however. – Ali Oct 23 '14 at 16:14
1

You can do this, but it's a bit fragile

foo.sh will look like this

#! /bin/bash
declare "$@"       # evaluate the params as variable declarations
bar $bar_args      # not quoted!
baz $baz_args      # not quoted!

Then, ./foo.sh bar_args="-x -v message=hello" baz_args="-d -m" will work like you hope.

Do not attempt to pass a message with whitespace in it, can't be done in this manner.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.