0

I have a bash script where I'm trying to pass posix style arguments with quoted values down to another script called within. On the command-line I might type:

somescript --foo="bar baz"

This means with the argument having the key foo, the value is bar baz. Within somescript, you might think this would work:

innerscript "$@"

However, this re-quotes the entirety of each argument, both key and value chunked together, not just the value. So innerscript receives "--foo=bar baz" and believes you are trying to pass the key named foo=bar baz with an empty value.

It's not good enough to tell bash "re-quote all the passed in arguments". I need to tell bash "re-quote all passed in arguments exactly how they were quoted before". Don't change the position of my quotes, bro!

Toddius Zho
  • 624
  • 6
  • 12

3 Answers3

3

The problem is in innerscript, then. There is no difference between:

innerscript --foo="bar baz"
innerscript "--foo=bar baz"
innerscript --foo=bar\ baz
innerscript --foo=bar' 'baz

or, undoubtedly, a number of other alternatives. Inside innerscript, $1 (in shell notation) contains just 13 characters: --foo=bar baz. Incidentally, the same holds for somescript; when you invoke it as shown, it does not see the double quotes. They are handled by (and removed by) the shell.

To see this, try:

echo --foo="bar baz"
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • The problem was with my understanding of innerscript. You were right. It did not have completely position-independent options like I thought it did. – Toddius Zho Sep 19 '11 at 23:05
1

You can't do that.

Scripts receive arguments. When the shell parses that line, it passes the first argument as: "--foo=bar baz". You cannot do anything to prevent that. But I don't see why that causing any problems, you can split the argument based on =.

# function test { echo $1; }
# test a"b""c"'d'\e
abcde
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0

For parsing arguments and options use getopt command.

Note1: getopt (gnu command) is enhanced getopts (defined in POSIX).

Note2: --long-options are GNU-style, not POSIX

Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
  • See [Using getopts in bash script to get long and short command line options](http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options/402413#402413). – Jonathan Leffler Sep 17 '11 at 00:24