Monday, December 1, 2014

Handle multiple return values in bash

Some times a command may return multiple values such as following example:

snmpwalk -v2c -c public 10.0.1.1 load
UCD-SNMP-MIB::laLoadFloat.1 = Opaque: Float: 0.260000
UCD-SNMP-MIB::laLoadFloat.2 = Opaque: Float: 0.110000
UCD-SNMP-MIB::laLoadFloat.3 = Opaque: Float: 0.030000

Following methods can be used to handle this case and print out 1, 5, and 15 minutes load in bash, and all of them have the identical output.

1. Set positional parameters:
load=`snmpwalk -v2c -c public 10.0.1.1 load | awk '{print $5}'`
set $load
printf '%-8s %7s %7s %10s\n' "Load:" $1 $2 $3

Note: Another way to assign return value to load
load=$(snmpwalk -v2c -c public 10.0.1.1 load | awk '{print $5}')

2. Multiple variable assignment:
read load_1 load_5 load_15 <<< `snmpwalk -v2c -c public 10.0.1.1 load | awk '{print $5}'`
printf '%-8s %7s %7s %10s\n' "Load:" $load_1 $load_5 $load_15

3. Array:
load=(`snmpwalk -v2c -c public 10.0.1.1 load | awk '{print $5}'`)
printf '%-8s %7s %7s %10s\n' "Load:" ${load[0]} ${load[1]} ${load[2]}

No comments: