On Monday, October 15, 2012 8:54:39 PM UTC+8, (unknown) wrote:
> This is due to a bug in some shell versions and lengthily explained in "exec magic" here:
>
>
>
>
http://wiki.tcl.tk/812
Great! The answer:
The incantation looks like this:
exec wish "$0" ${1+"$@"}
Here's how it works:
Each argument to sh is numbered $1, $2, $3, ... $9.
$0 is the name of the script. We put it in quotes to preserve whitespace and other weird characters.
The special variable $* expands to all the arguments. However, it expands *unquoted*, meaning that spaces will be lost in the expansion.
This means that the naive:
exec wish "$0" $*
will not work properly if any argument has a space in it. Likewise, using "$*" will fail because that will expand to a single argument.
The special form "$@" was introduced (the quotes are part of it) to work around this problem. This form expands to all the arguments, but properly (and individually) quoted. So why doesn't the following attempt work?
exec wish "$0" "$@"
The reason is that some versions of sh have a bug. If there are no arguments, these broken sh's will still expand "$@" into a single empty argument. Oops.
The sh syntax ${VAR+VALUE} expands to VALUE if $VAR is set, and nothing otherwise. We abuse this syntax to work around the buggy sh implementations. Recall that the first argument is named $1. If it exists, then we use "$@"; otherwise we do nothing:
exec wish "$0" ${1+"$@"}
The above is my interpretation. No doubt further refinements and clarifications are in order.