0

I have an issue in my output using snmpwalk so i'm trying in this script:

var=`snmpwalk -v2c -c private ${ip} .1.1.1.6`
echo "${hostname}=>${var}"

to have this output:

R1=>Gauge32: 240
R1=>Gauge32: 293
R1=>Gauge32: 255
R1=>Gauge32: 25

but actually i have this output :

R1=>Gauge32: 240
Gauge32: 293
Gauge32: 255
Gauge32: 25

so how can i have the output that i need in bash

1

It isn't working how you want as you are printing hostname before all the lines stored in the string $var. instead of looping and printing hostname before each line.

Here is one way to loop through them using a pipe and awk

snmpwalk -v2c -c private ${ip} .1.1.1.6 | awk -vHost="${hostname}" '{print Host"=>"$0}'
1

Instead of storing the output as a whole (with the embedded newline characters) in a scalar variable, you could (I didn't say you should) store lines in an array variable.

With ksh93, mksh, bash, zsh in sh emulation:

IFS='
' # split on newline
set -f
var=($(snmpwalk -v2c -c private "$ip" .1.1.1.6))

And then use printf like:

printf "$hostname=>%s\n" "${var[@]}"

That assumes however that $hostname doesn't contain percent or backslash characters.

rc and zsh make it easier:

  • rc:

    var = (``('
    '){snmpwalk -v2c -c private $ip .1.1.1.6})
    printf %s\n $hostname'=>'^$var
    
  • zsh:

    var=(${(f)"$(snmpwalk -v2c -c private $ip .1.1.1.6)"})
    printf '%s\n' $hostname'=>'$^var
    

(note that all those solutions ignore empty lines)

0

I don't think it's a good idea to assign the whole output of the command to a variable and then do the formatting. But if you want to do so you can use printf to do the formatting. The key is to expand hostname inside the format string, so that only the list of the type-value pairs in var will be affected by the format specifiers (%s and %d in this case), and printf guarantees the reuse of the format specifiers for every data pair:

var=`snmpwalk -v2c -c private ${ip} .1.1.1.6`
printf "${hostname}=>%s %d\n" ${var}

(Note: There's no quotes around ${var} is this case.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.