How to tell the tool iftop to print once a snapshot of active connections without cycling while in text mode?
iftop -t -i eth2
It seems there is no way to tell iftop -t to print one chunk and not to loop.
For comparison: top -b -n 1 can do what you want, the relevant option is -n 1. It's a different tool, but this example shows how easy it can be when the tool supports the option (note: iftop understands -n but it's a different, unrelated option).
Still you can parse the output and stop after the first chunk. In my Debian 10 iftop -t terminates each chunk with a line consisting of many = characters. It seems ^== is a good regex to detect the end of a chunk without false positives.
This command exits after the first chunk:
iftop -t -i eth2 | sed '/^==/ q'
Alternatively:
iftop -t -i eth2 | awk '{print; if ($0 ~ "^==") exit}'
To exit after the Nth chunk we need more complex code. In the following example N is 3. Adjust n=3 to your needs:
iftop -t -i eth2 | awk -v n=3 '
BEGIN {if (n<=0) exit}
{
print
if ($0 ~ "^==") n--
if (n<=0) exit
}'
Notes:
awk (or sed) exits, iftop is not notified immediately. It gets SIGPIPE only when it tries to write something more to the now broken pipe. This means the whole command will stall until iftop generates yet another chunk (which will not be printed). This is normal. Optimizing iftop in this matter makes little sense, it's not like it's going to stall forever. Compare how it makes sense for tail.iftop -t where full chunks appear with pauses in between. The buffering between iftop and awk is to blame. In my tests stdbuf -oL iftop … helped.iftop prints some messages to stderr. They will not go through the pipe, unless you use iftop … 2>&1 | ….