Issue
I'm writing a small script that needs to run a program that outputs multiple lines, and then display the count of those lines. The program, however, can take several seconds to run and I would rather not run it twice, once for the output and another for the count.
I can do it running the program twice:
#!/bin/bash
count=$(program-command | wc -l)
program-command
printf "$count lines"
Is there a way to get the count and output while only running the program once? This output has formatting, so ideally that formatting (colors) would be preserved.
Solution
Use tee
and process substitution:
program-command | tee >(wc -l)
To preserve color, prefix the command with script -q /dev/null
as per this answer:
script -q /dev/null program-command | tee >(wc -l)
Answered By - Ben Answer Checked By - Katrina (WPSolving Volunteer)