Bash Pipeline Puzzle: Green, Blue, Or Blue Green?

[Marek Gibney] poses an interesting puzzle. What does the following bash command line print?

( echo red ; echo green 1>&2 ) | echo blue

You’d like to think it prints three lines: red, green, and blue. But would you be surprised to find out that it can sometimes output “blue green” and sometimes just output blue. The first surprise is that it isn’t deterministic. But the second thing that is surprising is the sometimes the entire left-hand part of the line doesn’t do anything. [Chris Siebenmann] did the analysis and explains what’s going on in a recent blog post.

Before you click the link or read further, you might want to see if you can deduce what’s going on. Give up? Here’s a hint: Part of the solution hinges on the fact that echo is built into the shell.

Continue reading “Bash Pipeline Puzzle: Green, Blue, Or Blue Green?”