Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

🍿 Pipe multiple outputs into one in bash

Snacks (🍿) are my collection of recipes for solving problems. Often recorded (and cleaned up) from actual discussions where I'm involved in helping others with technical problems. Not all solutions are mine but I started collecting them in one place because you never know when you need one.


How to run multiple commands in bash, collect their outputs and pipe them into a single command?

For example, let's say we want to roll six-sided die three times and calculate the sum.

We can generate a random number between 1 and 6 using shuf with shuf -i1-6 -n1.

To run these three and combine their outputs into the same standard output, we wrap them into parentheses

(shuf -i1-6 -n1; shuf -i1-6 -n1; shuf -i1-6 -n1)

We can then calculate the sum with awk:

(shuf -i1-6 -n1; shuf -i1-6 -n1; shuf -i1-6 -n1) | awk '{s+=$1} END {print s}'