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

var=`snmpwalk -v2c -c private ${ip} .`
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


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} . | awk -vHost="${hostname}" '{print Host"=>"$0}'

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:

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

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 .})
    printf %s\n $hostname'=>'^$var
  • zsh:

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

(note that all those solutions ignore empty lines)


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} .`
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.