views:

135

answers:

2

Hello!

I want to write a wrapper bash script, and to pass all arguments to a called program. I was very sure, that this works correctly:

#!/bin/sh
someProgam $@

But when passing exotic arguments (empty, unescaped, in quotes, ...) this fails.

For example: without the wrapper script, someProgram "1 2" 3 results in the arguments
[1 2] and [3].
But called from the script, I get [1], [2], [3].

Braces are just for visualization.

NOTE: It's a Java program, which is called. But I think it doesn't matter.

+5  A: 
#!/bin/sh
someProgram "$@"

See also the bash docs on special parameters.

BTW1, "$@" is not specific to bash. You can probably rely on "$@" in cross-platform sh scripts to be run just about anywhere.

BTW2, in case this happens to be the last line in that script, you can save your operating system a few bytes and an entry in the process table by changing the line to something like

exec someProgram "$@"
ndim
Thanks! It worked!
java.is.for.desktop
+4  A: 

to augment ndim's answer: the behavior of "$@" is not specific to bash. it's prescribed by the Single Unix Specification:

2.2.3 Double-Quotes

Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters dollar sign, backquote, and backslash, as follows:

The parameter '@' has special meaning inside double-quotes and is described in Special Parameters.

2.5.2 Special Parameters

Listed below are the special parameters and the values to which they shall expand. Only the values of the special parameters are listed; see Word Expansions for a detailed summary of all the stages involved in expanding words.

@

Expands to the positional parameters, starting from one. When the expansion occurs within double-quotes, and where field splitting (see Field Splitting) is performed, each positional parameter shall expand as a separate field, with the provision that the expansion of the first parameter shall still be joined with the beginning part of the original word (assuming that the expanded parameter was embedded within a word), and the expansion of the last parameter shall still be joined with the last part of the original word. If there are no positional parameters, the expansion of '@' shall generate zero fields, even when '@' is double-quoted.

just somebody
Thanks for pointing out that `"$@"` works on (most, if not all) non-bash `sh` implementations. I have added a small note to my answer.
ndim