Bash – how to keep consumer alive even if producer exits

bashpipeshell

Say we have a simple pipeline:

a | b

say, a exits – is there a surefire way to keep b alive for an arbitrary amount of time (to complete a task etc).

Best Answer

b would not be terminated by a terminating.

$ { echo hello; } | { read message; printf 'got "%s"\n' "$message"; sleep 5; echo "ok, I'm done"; }
got "hello"
ok, I'm done

Here, a (the echo hello) would simply output a string and terminate. The right hand side of the pipe (b) would read the string, output it, sleep for a while, and then do its final echo before terminating.

If b was terminated when a was, it would never have time to do what it needed to do. The only thing b can't do here is to read more data from its standard input (an extra read at the end would get end-of-file immediately).


In the other scenario (not mentioned in the question), where b terminates before a, a would receive a PIPE signal if it tried to write to its standard output (across to the non-existing b process) and terminate from that (by default).

If it didn't try to write to the pipe, a would continue running until done.

Related Question