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?



You must log in to answer this question.

Browse other questions tagged .