Quickie about Shell Parameter Expansion

Daniel Qarras dqarras at yahoo.com
Tue Oct 16 18:07:20 UTC 2007


Hi Cameron,

thanks for the excellent answer, FAQ material!

Cheers!


--- Cameron Simpson <cs at zip.com.au> wrote:

> On 15Oct2007 13:59, Daniel Qarras <dqarras at yahoo.com> 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 at zip.com.au> 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 at csd.harris.com>
> 
> -- 
> fedora-list mailing list
> fedora-list at redhat.com
> To unsubscribe: https://www.redhat.com/mailman/listinfo/fedora-list
> 



       
____________________________________________________________________________________
Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
http://farechase.yahoo.com/




More information about the fedora-list mailing list