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

Re: newline in command-line argument?



On Fri, Aug 09, 2002 at 05:22:22PM -0700, Kendall Shaw wrote:
> Craig Dickson <crdic@pacbell.net> writes:
> > The quotes in echo "$A" are not optional, by the way, if you want the
> > newline displayed correctly.
> 
> That's it. Hmm. Why does the newline get eaten without the quotes?

Well, it doesn't get eaten as such. It just gets treated in a different
way.

One of the stages in parsing a command line (see "EXPANSION" in bash(1))
is word splitting. This splits the command line into words based on the
value of the IFS variable, which is <space><tab><newline> by default.
Each word is then passed as a single argument to the command you're
invoking: if you've programmed in C then you'll recognize each word as
an element of argv[].

So, if you simply type:

  echo $A

... then $A is expanded into 'asdf<newline>fdsa', but word splitting
causes the three words on the command line to be 'echo', 'asdf', and
'fdsa'. 'echo' then simply prints out each of its arguments separated by
a space. For a demonstration that this is what is happening, try setting
IFS to a single space (although correct quoting is a much better way to
control expansion than setting IFS, with a few very rare exceptions).
Word splitting isn't performed on expansions that happened within double
quotes, so the newline is preserved verbatim there.

One of the keys to good shell programming is to quote all expansions
unless you have a good reason not to do so.

Cheers,

-- 
Colin Watson                                  [cjwatson@flatline.org.uk]



Reply to: