help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] What does this idiom mean


From: Greg Wooledge
Subject: Re: [Help-bash] What does this idiom mean
Date: Wed, 8 Feb 2012 14:44:56 -0500
User-agent: Mutt/1.4.2.3i

On Wed, Feb 08, 2012 at 01:24:39PM -0600, Bill Gradwohl wrote:
> Somewhere, I believe, I saw the following:
> 
> address@hidden@}
> 
> I understand what address@hidden is but everything from the + onward is a 
> mystery.

First of all, that's not very useful as written, and should probably be:

address@hidden"$@"}

or more commonly,

${1+"$@"}

> When I key it into a script it doesn't fail as a syntax error, so I suspect
> its legal but I don't know what its trying to say.

I'll focus on ${1+"$@"} since that's what people actually use.

The first part, ${1+, means "see whether $1 is defined or not".  If it's
defined, then we move on to the second part.  If it's not defined, then
we drop the entire expression, and no substitution occurs.

If $1 is defined, then we use the second part, "$@".  This expands to
a list of words, one for each positional parameter, as if we had written
"$1" "$2 "$3" ... and magically known when to stop writing.

So then you ask: why not simply use "$@" in the first place, since this
already does what we want?  The answer is that in certain ancient Bourne
shells, there was a bug, in which "$@" sometimes produced the wrong
result if there were no arguments (it would expand to a list with one
word in it, the empty string, rather than a list of zero words).  So
${1+"$@"} is a workaround for that bug.

If you are targetting POSIX or Bash, you can use "$@" safely.  If you are
targetting Bourne, you should use ${1+"$@"} just in case.

This would be used in a wrapper script, such as:

#!/bin/sh
SOME_VAR=foo
export SOME_VAR
exec /the/real/program ${1+"$@"}



reply via email to

[Prev in Thread] Current Thread [Next in Thread]