0

I am baffled by how piping in bash works. Take a random string generator, for example:

tr -dc 'A-Z0-9' </dev/urandom

spawned tr process that reads from /dev/urandom indefinitely, as far as /dev/urandom providing with output, until something interrupt it. Now take this:

tr -dc 'A-Z0-9' </dev/urandom | fold -w 8 | head -n 1

Immediately outputs the first line of that seemingly indefinite output of uppercase alphanumeric characters folded in 8 symbols per line. That is generated 8 random uppercase alphanumeric characters. I sort of have the intuition from the head standpoint: it waits for the first line and it's the only thing it waits for from its stdin.

man bash says:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

How exactly head tells fold and it tells tr that that's enough? Does fold send a termination signal to the tr process? Or is it some more complicated behavior, like say head's /dev/stdin points to the same stream as fold's /dev/stdout, and when head closes the stream, fold gets a termination signal? What's happens to those subshells when they stack is such pipeline?

And a side question: how should I write my bash scripts so that they work properly when stacked in a pipeline?

  • The "side" question of properly stacking pipelines probably deserves its own separate question. – Jeff Schaller Apr 29 '20 at 18:29
  • See, for example, https://unix.stackexchange.com/questions/513657/understanding-piped-commands-in-unix-linux/513662#513662 and https://unix.stackexchange.com/questions/29964/are-linux-utilities-smart-when-running-piped-commands/29976#29976 and https://unix.stackexchange.com/questions/243350/why-does-using-yes-on-bash-pipelines-not-cause-infinite-loops/243352#243352 and https://unix.stackexchange.com/questions/84813/what-makes-a-unix-process-die-with-broken-pipe/84828#84828 – Jeff Schaller Apr 29 '20 at 18:32
  • tl;dr. Head exits, so its stdin is closed. Fold writes to stdout, gets a SIGPIPE, doesn't catch it, gets killed. Rinse and repeat. – Paul_Pedant Apr 29 '20 at 18:44

0 Answers0