Bash – Count lines of non-terminating input

bashwc

Is there any way to count the lines of a non-terminating input source? For example, I want to run the following for a period of time to count the number of requests:

ngrep -W byline port 80 and dst host 1.2.3.4 | grep ":80" | wc

Obviously, that doesn't work. When I Ctrl+C kill that, I'm not going to get any output from wc. I would rather avoid creating a file if I can.

Best Answer

Typing Ctrl+C from the terminal sends SIGINT to the foreground process group. If you want wc to survive this event and produce output, you need to have it ignore the signal.

The solution is to run wc in a subshell and have its parent shell set SIGINT to be ignored before running wc. wc will inherit this setting and not die when SIGINT is sent to the process group. The rest of the pipeline will die, leaving wc reading from a pipe that has no process on the other end. This will cause wc to see EOF on the pipe and it will then output its counts and exit.

ngrep -W byline port 80 and dst host 1.2.3.4 | grep ":80" | (trap '' INT ; wc)
Related Question