Linux

精確寫入 bash 腳本輸出的值

  • July 4, 2019

我有以下命令:

$ snmpnetstat -v2c -c public -Cs -Cp udp 10.10.0.32 

有輸出:

udp:
          198 total datagrams received
           65 datagrams to invalid port
            0 datagrams dropped due to errors
          265 output datagram requests

我想編寫一個返回以下內容的 bash 腳本:

Received Datagrams: 198 Invalid port:65 Dropped datagrams: 0 Datagram requests: 256

我開始:

#!/bin/bash

#!/bin/bash
rs=$(snmpnetstat -v2c -c public -Cs -Cp udp 10.10.0.32)
ReceivedDatagrams=$(echo $rs | cut -d"/" -f1)
InvalidPort=$(echo $rs | cut -d"/" -f2)
DroppedDatagrams=$(echo $rs | cut -d"/" -f3)
DatagramRequests=$(echo $rs | cut -d"/" -f4)
echo "Received Datagrams:$ReceivedDatagrams Invalid port:$InvalidPort Dropped datagrams:$DroppedDatagrams Datagram requests:$DatagramRequests"



echo "Received Datagrams:$ReceivedDatagrams Invalid port:$InvalidPort Dropped datagrams:$DroppedDatagrams Datagram requests:$DatagramRequests"

輸出是:

   zsz@bme-ib112-05:~/bash_scripts$ ./script.sh         
Received Datagrams:udp: 242 total datagrams received 37 datagrams to invalid port 0 datagrams dropped due to errors 638 output datagram requests Invalid port:udp: 242 total datagrams received 37 datagrams to invalid port 0 datagrams dropped due to errors 638 output datagram requests Dropped datagrams:udp: 242 total datagrams received 37 datagrams to invalid port 0 datagrams dropped due to errors 638 output datagram requests Datagram requests:udp: 242 total datagrams received 37 datagrams to invalid port 0 datagrams dropped due to errors 638 output datagram requests

輸出值一遍又一遍地重複,而不是我想要的。

您的腳本有幾個問題。首先,echo吞下所有換行符,除非您指定-e開關。所以在這之後:

rs=$(snmpnetstat -v2c -c public -Cs -Cp udp 10.10.0.32)
echo $rs

輸出將是:

udp: 198 total datagrams received 65 datagrams to invalid port 0 datagrams dropped due to errors 265 output datagram requests

其次,您將 指定/為分隔符cut,但輸出不包含此字元,因此將其用作分隔符是沒有用的。

第三,您想從輸出中刪除某些欄位,但這不起作用,主要是因為第一點。沒有吞下echo換行符,它可以工作,但是您只需要剪切第一個欄位,因為對於每一行,該欄位將包含您需要的數字。但是您仍然需要將結果行轉換為數組,並使用該數組輸出您需要的內容。

像這樣:

output=$(snmpnetstat -v2c -c public -Cs -Cp udp 10.10.0.32)
thearray=($(echo -e "$output"|tail -n +2|awk '{print $1}'))
echo "Received Datagrams:${thearray[0]} Invalid port:${thearray[1]} Dropped datagrams: ${thearray[2]} Datagram requests: ${thearray[3]}"

引用自:https://serverfault.com/questions/973825