Sunday, 1 September 2013

HOWTO add a shell script wrapper and preserve quoting for parameters

If you ever find yourself in the situation where you have to add a shell script wrapper over a command, but the parameters' quoting gets lost and you end up with the wrong parameters in the wrapped command/tool, you might want to read this post.

On my system I have some command line tools which are Windows only and, in order to easily use the same build system as on Windows on my Linux machine I added a wrapper script which invokes wine on the commands and made symlinks to the wrapper with the file names as the tools, but without the '.exe' suffix.

Of course, I wanted to properly pass the parameters through the wrapper to the tools so I wrote (note the bold text):
#!/bin/sh
wine $0.exe "$@"
So the answer is: use $@ and quote like I did in the code above and the parameters will be passed correctly.




Update: stbuehler suggested to use exec to replace the shell process with wine with this construct:
Use:
#!/bin/sh
exec wine $0.exe "$@"

Thanks for the suggestion.

2 comments:

stbuehler said...

Use:
#!/bin/sh
exec wine $0.exe "$@"

That way the shell process gets replaced by wine.

Elessar said...

Yes, it is often said that $@ and $* are equivalent, but they are not, at least not when quoted: "$*" is all the arguments in one single string, whereas "$@" has the (artificial) super-power of separating the arguments.