温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to return precisely output values of bash script has command

python - 如何精确返回bash脚本的输出值有命令

发布于 2020-03-27 10:27:27

我有以下命令:

$ 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脚本:

bash脚本的期望输出:

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

我开始于:

#!/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"

输出为:

    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

输出值不断重复,而不是我想要的。

查看更多

查看更多

提问者
Tom Gerrard
被浏览
71
hyperTrashPanda 2019-07-03 21:50

我无法重新创建snmpnetstat命令的确切输出,所以我只是将终端输出复制/粘贴到file中tmp

以下脚本使用您的逻辑来完成您要求的工作

我建议接受Shellter和Ed Morton的建议,并仔细研究报价变量如何工作以不允许在空格/换行符中进行扩展,并使用Awk作为更健壮和易于扩展的解决方案。

#!/bin/bash

rs="$(cat tmp)"

# You have to quote "$rs" so newlines don't break
ReceivedDatagrams="$(echo "$rs" | cut -d$'\n' -f2 | tr -s ' '| cut -d' ' -f2)"
InvalidPort="$(echo "$rs" | cut -d$'\n' -f3 | tr -s ' '| cut -d' ' -f2)"
DroppedDatagrams="$(echo "$rs" | cut -d$'\n' -f4 | tr -s ' '| cut -d' ' -f2)"
DatagramRequests="$(echo "$rs" | cut -d$'\n' -f5 | tr -s ' '| cut -d' ' -f2)"

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

发布
问题

分享
好友

手机
浏览

扫码手机浏览