Shell

基於 grep 結果的條件回顯

  • November 17, 2020

我有以下命令將輸出我在給定埠上有多少個連接:

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

將您的計數分配給變數

count=$(netstat -an | grep ESTABLISHED | grep -w <Port Number> | wc -l)
if [[ $count -gt 0 ]]; then #issue your echo or printf

引用自:https://unix.stackexchange.com/questions/620171