1

I have two programs in bash:

{ { sleep 1s; kill 0; } | { while true; do echo "foo"; done; kill 0;} }

and

{ { while true; do echo "foo"; done; kill 0; } | { sleep 1s; kill 0; } }

(just changed order).

How is it possible that the first one writes a lot of "foo" in the output and the second one writes nothing?

dogbane
  • 266,786
  • 75
  • 396
  • 414

3 Answers3

2

Connecting two processes by a pipe redirects the output from the first to the second. Thus, connecting a process which writes output to a process that does nothing that output means no output occurs.

By contrast, connecting a process which does nothing to a process that generates output, the latter will proceed to generate output as usual.

By the way, what's the purpose of the kill 0 lines? I doubt very much that they serve a useful purpose here.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
2

The second one does output foo, you just don't see it because it is piped to your second command.

You can prove this by redirecting to a file:

$ { { while true; do echo "foo" >> /tmp/f; done; kill 0; } | { sleep 1s; kill 0; } }
$ wc -l /tmp/f
56209
dogbane
  • 266,786
  • 75
  • 396
  • 414
0

that's because in the second command you are piping the output of a echo as the input of { sleep 1s; kill 0; }

What is a simple explanation for how pipes work in BASH?

Community
  • 1
  • 1