2012-07-23 94 views
2

我有一個awk腳本,用於獲取系統中總的eth中斷的數量。在bash中使用awk變量

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

在bash結束時,我有core_count和totals數組。但是接下來,我需要使用這些變量,我怎樣才能在腳本的其餘部分使用它們?換句話說,您如何將它們全球化?

回答

1
#!/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]} 
+1

感謝@perreal它是非常有用 – barp 2012-07-23 06:24:26

+0

爲了避免重複'回聲。| ..'。代碼,'set $ output'將標記輸出並用標記值替換'$ 1','$ 2'等。還要注意'echo'有問題,應該避免。一般來說,至少應引用「回聲」字符串。 – tripleee 2012-07-23 07:28:25

2

你不能。回聲出來,和他們拉在

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