Warm tip: This article is reproduced from stackoverflow.com, please click
bash python shell ubuntu ubuntu-18.04

How to return precisely output values of bash script has command

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

I have the following command:

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

that has the terminal output:

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

I want to write a bash script that returns the following:

the desired output of bash script:

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

I started with:

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

The output is:

    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

The output values are repeating over and over and not as I wanted.

Questioner
Tom Gerrard
Viewed
230
hyperTrashPanda 2019-07-03 21:50

I can't recreate the exact output of the snmpnetstat command, so I just copy/pasted your terminal output into a file tmp.

The following script does the job you requested on my end, using your logic

I'd recommend taking shellter's and Ed Morton's advice and look through how quoting variables works to disallow expansion in whitespace/newlines, and using Awk for a more robust and easily extendable solution.

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