简体   繁体   English

在bash脚本中将snmpbulkwalk输出分配给关联数组

[英]Assign snmpbulkwalk output to associative array in bash script

I've searched high and low for an answer but the solution continues to evade me. 我一直在寻找答案,但解决方案仍在逃避我。 Below are the results of an snmpbulkwalk that I'm running against a local server. 以下是我针对本地服务器运行的snmpbulkwalk的结果。

snmpbulkwalk -v2c -Oqs -m EGT-VIPr-TRx -c <community> <ip> egtViprOutputMuxSecDestPort | sed -e 's/egtViprOutputMuxSecDestPort\.//g'
Output
1 2001
4 2002
5 2003
8 2004

My goal is to assign this output to an associative array in bash (ex array[1]=2001, array[4]=2002, ... ). 我的目标是将此输出分配给bash中的关联数组(例如array[1]=2001, array[4]=2002, ... )。 Below is the code that I've used in the past when assigning snmpbulkwalk output to a standard array. 下面是我过去将snmpbulkwalk输出分配给标准数组时使用的代码。 However I've had no success with associative arrays. 但是我在关联数组方面还没有成功。

declare -A array
array=($(snmpbulkwalk -v2c -Oqs -m EGT-VIPr-TRx -c <community> <ip> egtViprOutputMuxSecDestPort | sed -e 's/egtViprOutputMuxSecDestPort\.//g'))
echo ${array[1]}

Output
array: 1: must use subscript when assigning associative array
array: 2001: must use subscript when assigning associative array
array: 2: must use subscript when assigning associative array
array: 2002: must use subscript when assigning associative array
array: 3: must use subscript when assigning associative array
array: 2003: must use subscript when assigning associative array
array: 4: must use subscript when assigning associative array
array: 2004: must use subscript when assigning associative array

Any assistance would be greatly appreciated. 任何帮助将不胜感激。

I've found a workable solution and I'm posting the answer for future reference. 我找到了可行的解决方案,并将答案发布给以后参考。 After much trial and error a while read loop accomplished my ultimate goal. 经过多次尝试和错误,一段while read循环实现了我的最终目标。

declare -A array

while read id value; do
        array[$id]=$value
done < <(snmpbulkwalk -v2c -Oqs -m EGT-VIPr-TRx -c <community> <ip> egtViprOutputMuxSecDestPort | sed -e 's/egtViprOutputMuxSecDestPort\.//g')

echo ${array[1]}

Output
2001

I struggled somewhat with the syntax for reading the output from snmpbulkwalk into my loop, but the code above works perfectly in my scenario. 我在将语法从snmpbulkwalk读取到我的循环中的语法上有些挣扎,但是上面的代码在我的情况下完美地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM