我有以下命令将输出给定端口上有多少个连接:
while true
do
echo -n "number of connections: "
netstat -an | grep ESTABLISHED | grep -w <Port Number> | wc -l
date
printf '\n'
sleep 0.3
done | grep -v "number of connections: 0"
如果连接数为 0,我不想打印任何内容。但是,由于日期打印在单独的行上,因此 grep 不适用于 date 命令。
这是一些示例输出:
Tue Nov 17 16:42:48 EST 2020
Tue Nov 17 16:42:49 EST 2020
number of connections: 1
Tue Nov 17 16:42:49 EST 2020
number of connections: 3
Tue Nov 17 16:42:49 EST 2020
number of connections: 2
Tue Nov 17 16:42:50 EST 2020
前两行是连接数为 0 时打印的内容,但是我想要的输出(基于上面的示例输出)只是:
number of connections: 1
Tue Nov 17 16:42:49 EST 2020
number of connections: 3
Tue Nov 17 16:42:49 EST 2020
number of connections: 2
Tue Nov 17 16:42:50 EST 2020
答案1
将您的计数分配给变量
count=$(netstat -an | grep ESTABLISHED | grep -w <Port Number> | wc -l)
if [[ $count -gt 0 ]]; then #issue your echo or printf