Linux: How do I delegate exotic commandline argume

2019-08-11 17:30发布

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.

2条回答
Ridiculous、
2楼-- · 2019-08-11 17:57

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.

查看更多
Bombasti
3楼-- · 2019-08-11 18:11
#!/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 "$@"
查看更多
登录 后发表回答