Re: Quickie about Shell Parameter Expansion

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

 



On 15Oct2007 13:59, Daniel Qarras <dqarras@xxxxxxxxx> wrote:
| just a quick question about shell parameter expansion: "$@" is obvious
| from, e.g., bash manual page but I'm puzzled when I've seen few time
| this sort of construct used: ${1+"$@"}
| 
| What's the difference of "$@" and ${1+"$@"} (in theory and in
| practice)? Any examples?

"$@", as you know, is a properly quoted version of the command line
arguments. If you call a script thus:

  the-script a b "c d"

then "$@" will get you three strings: "a", "b" and "c d".
Comapred to $*, which gets you 4 ("a", "b", "c" and "d") and
compared to "$*", which gets you one ("a b c d") like any other shell
variable. So "$@" is a bit of special magic.

However, historically, if there were _no_ command line arguments then "$@"
got you a single empty string (""). Presumably because it was felt that a
quoted string should never just disappear.

Thus the incantation ${1+"$@"}, which says: if $1 is defined, substitute
"$@"; if $1 is _not_ defined (i.e. there are no arguments) substitute
nothing. You'll find ${foo+bah} documented in the shell's PARAMETER
SUBSTITUTION section.

Now, with a bunch of modern shells $@ is more magic that it used to be;
it used to be that only a quoted "$@" did the magic thing, and an
unquoted $@ behaved like $* and any other variable. But for some recent
shells a bare $@ behaves the way you probably would have wanted "$@" to
behave, without the nasty "no arguments" corner case.

However, for portability some of us old timers write ${1+"$@"} because
it works everywhere reliably. Just learn to recognise and use it by
reflex instead of "$@". It means what you intended when you wrote "$@".

Cheers,
-- 
Cameron Simpson <cs@xxxxxxxxxx> DoD#743
http://www.cskk.ezoshosting.com/cs/

Don't have awk? Use this simple sh emulation:
    #!/bin/sh
    echo 'Awk bailing out!' >&2
    exit 2
- Tom Horsley <tahorsley@xxxxxxxxxxxxxx>


[Index of Archives]     [Current Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]     [Fedora Docs]

  Powered by Linux