精确写入 bash 脚本输出的值

精确写入 bash 脚本输出的值

我有以下命令:

$ 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

输出值不断重复,并不像我想要的那样。

答案1

您的脚本有几个问题。首先,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]}"

答案2

bash不允许在=赋值语句周围留空格:

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

最后,对于空白比...bash更加挑剔。python

答案3

也许是这样的

#!/bin/bash
rs=$(snmpnetstat -v2c -c public -Cs -Cp udp 10.10.0.32)
# Create an array with one numberset per entry
num=($(grep -o "[0-9]*" file.txt))
# text output using the values within the array
echo "Received Datagrams:${num[0]} ReceivedDatagrams Invalid port:${num[1]} Dropped datagrams: ${num[2]} Datagram requests:${num[3]}"

相关内容