barp
barp

Reputation: 6929

using the awk variable in bash

I have an awk script that takes the number of total eth interrupts in the system.

#!/bin/bash

FILE="/proc/interrupts"

awk 'NR==1 {
core_count = NF 
print "core count: ", core_count
next
}

/eth/ {
 for (i = 2; i <= 2+core_count; i++)
 totals[i-2] += $i
}

END {
print "Totals"
for (i = 0; i < core_count; i++)
printf("CPU%d: %d\n", i, totals[i])
}
' $FILE

At the end of this in bash, I have the core_count and the totals array. but then, I need to use these variables, how can I use them at the rest of the script?In other words how can you globalize them?

Upvotes: 2

Views: 964

Answers (2)

perreal
perreal

Reputation: 97948

#!/bin/bash

FILE="/proc/interrupts"

output=$(awk 'NR==1 {
core_count = NF 
print core_count
next
}

/eth/ {
 for (i = 2; i <= 2+core_count; i++)
 totals[i-2] += $i 
}

END {
for (i = 0; i < core_count; i++)
  printf("%d\n", totals[i])
}
' $FILE)
core_count=$(echo $output | cut -d' ' -f1)
output=$(echo $output | sed 's/^[0-9]*//')
totals=(${output// / })
echo CC: $core_count total0 ${totals[0]} total1 ${totals[1]}

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

You can't. Echo them out and pull them in.

{ read core_count ; read -a totals ; } < <(echo -e "2\n4 5")

Upvotes: 2

Related Questions