Bash – Count Number of Lines of Output from Previous Program

bashcommand linedebianshell

I'm trying to count the number of lines of output a certain program produces. The problem is, the program takes a long time to run, and I want to display the output to the user. Is there a way to count the number of lines the last command outputted?

I could do program | wc -l but that wouldn't show the output to the user. So as far as I know, I have to do program; program | wc -l – but the program takes at least a minute to run, so I don't want to have to do it more than once just to show a line count at the bottom.

EDIT:

  • Is there a way of showing the output as it happens (line by line) and then returning a count at the end?

Best Answer

You can use tee to split the output stream sending one copy to wc and the other copy to STDOUT like normal.

program | tee >(wc -l)

The >(cmd) is bash syntax which means run cmd and replace the >(cmd) bit with the path to (a named pipe connected to) that program's STDIN.