bug-bash
[Top][All Lists]
Advanced

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

Re: Not so useless use of cat


From: Bob Proulx
Subject: Re: Not so useless use of cat
Date: Fri, 12 Sep 2014 18:12:13 -0600
User-agent: Mutt/1.5.23 (2014-03-12)

Ralf Goertz <me@myprovider.invalid> wrote:

Since you have used an invalid address I assume you are reading the
mailing list via a web archive or other means and did not CC you.

> Why do I need cat (the second on) here?

You don't.

> $ echo first >file1
> $ echo second >file2
> $ (for i in file[12] ; do cat "$i" > /dev/stdout ; done) | cat > both

Why do you want >/dev/stdout there?

> $ cat both
> first
> second

Okay.

> If I omit the "| cat" after the loop I get

  (for i in file[12] ; do cat "$i" > /dev/stdout ; done) > both

> $ cat both
> second

Because the >/dev/stdout truncates the output.  It writes the first.
Then the second one truncates the file and then writes the second.
Remove that from the line and it will print both lines.

  (for i in file[12] ; do cat "$i" ; done) > both

> Even when using ">> both" instead of "> both" only "second" makes it
> into both. Why?

All that the >, >>, 2>&1, types of redirections do is to attach the
associated files with different files.  Once associated the further
actions such as truncation happen to those files.  Therefore the
truncation associated with >/dev/null truncates the file that on the
far right was >both.

Try this:

  (for i in file[12] ; do cat "$i" >> /dev/stdout ; done) > both

But really I think you are better off forgetting about >/dev/stdout.
That is almost like the useless use of cat.

And the subshell isn't needed either.  Use a list.

  { for i in file[12] ; do cat "$i" ; done ;} > both

> I would have thought that using a subshell should be
> enough to protect the both from being overwritten. 

The subshell isn't really part of the issue.  The issue is that the
file descriptor is attached and truncated and that is orthogonal to
process boundaries.

Hope that helps!

In the future please consider asking questions such as these on
help-bash@gnu.org for general discussion of bash shell scripting.  If
you expose a bug then report the bug to the bug reporting address.
The help-bash list is for help with bash scripting and this would have
been perfect there.

Bob



reply via email to

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