[Novalug] What is the name of a simple command|
Michael Henry
lug-user at drmikehenry.com
Wed Apr 8 06:49:15 EDT 2009
Mackenzie Morgan wrote:
> Of course, if your goal was just to add bar's contents to the end of
foo's
> and have it all stay in foo, just tweak the above for that:
> cat foo bar > foo
> or
> cat bar >> foo
The natural-seeming first invocation, ``cat foo bar > foo``
unfortunately doesn't work. Before ``cat`` executes, the shell has
already clobbered ``foo`` with the redirection operator. GNU ``cat`` is
smart enough to detect this problem and warn you after the fact::
$ echo "contents of foo" > foo
$ echo "contents of bar" > bar
$ cat foo bar > foo
cat: foo: input file is output file
$ cat foo
contents of bar
But notice that the original contents of ``foo`` have been clobbered,
and only the contents of ``bar`` made it into ``foo``. The second
invocation, ``cat bar >> foo``, properly appends ``bar`` to ``foo``.
The reason ``cat`` warns you about this problem despite the fact that
it's too late to avoid clobbering your input file is to avoid infinitely
long files:
$ cat bar foo >> foo
cat: foo: input file is output file
If ``cat`` were unable to notice that ``foo`` was both input and output,
it could create an infinitely long file. The contents of ``bar`` would
first be placed into ``foo``, then ``foo`` would be opened for input and
the most recently written ``contents of bar`` would be read from ``foo``
and re-written to ``foo``. But now, ``foo`` contains another copy of
``contents of bar``, so it would be copied again, ad infinitum.
Michael Henry
More information about the Novalug
mailing list