如何从命令变量在bash中创建数组?

时间:2012-01-05 22:33:35

标签: arrays bash variables

我正在尝试将SNMP转换为数组,变量中的数据采用"data1 data2" "data3 data4"格式。基本上我只想要双引号之间的数据,无论可能有多少空格。

我一直在谷歌约一个半小时,无法弄清楚如何正确格式化阵列。

以下是我现在拥有的代码的信息......

IN=$(snmpwalk -Oqv -v2c -c$community $ipaddr .1.3.6.1.4.1.32050.2.1.26.2)
portdesc=($(echo $IN))

这确实将它放在一个数组中,但在尝试访问第一个数据集时,我得"data1而不是"data1 data2"。我可以作弊,只使用两个变量,但我宁愿以正确的方式做,只是引用我想要的项目的数组。 如果你可以帮助我,我将永远是伟大的。

echo "DEBUG0: ${portdesc[@]}"
echo "DEBUG1: ${portdesc[0]}"

DEBUG0: "Relay Output" "Expansion Power" "Expansion Tripped" "Switch Input" "Radio 1 Power" "Radio 2 Power" "Radio 3 Power" "Radio 4 Power" "Radio 1 Sync" "Radio 2 Sync" "Radio 3 Sync" "Radio 4 Sync" "Radio 1 Tripped" "Radio 2 Tripped" "Radio 3 Tripped" "Radio 4 Tripped" "SyncPipe Power" "SyncPipe Tripped" "Switch to NMEA" "2D Fix" "3D Fix" "DGPS Fix" "1PPS Active" "Radio 1 Power" "Radio 2 Power" "Radio 3 Power" "Radio 4 Power" "Radio 1 Sync" "Radio 2 Sync" "Radio 3 Sync" "Radio 4 Sync" "Radio 1 Tripped" "Radio 2 Tripped" "Radio 3 Tripped" "Radio 4 Tripped" "SyncPipe Power" "SyncPipe Tripped" "Switch to NMEA" "2D Fix" "3D Fix" "DGPS Fix" "1PPS Active" "Radio 1 Power" "Radio 2 Power" "Radio 3 Power" "Radio 4 Power" "Radio 1 Sync" "Radio 2 Sync" "Radio 3 Sync" "Radio 4 Sync" "Radio 1 Tripped" "Radio 2 Tripped" "Radio 3 Tripped" "Radio 4 Tripped" "SyncPipe Power" "SyncPipe Tripped" "Switch to NMEA" "2D Fix" "3D Fix" "DGPS Fix" "1PPS Active"

DEBUG1: "Relay

来自CLI的SNMP命令

$ snmpwalk -O qv -v2c -c<community> <ip> .1.3.6.1.4.1.32050.2.1.26.2
"Relay Output"
"Expansion Power"
"Expansion Tripped"
"Switch Input"
"Radio 1 Power"
"Radio 2 Power"
"Radio 3 Power"
"Radio 4 Power"
"Radio 1 Sync"
"Radio 2 Sync"
"Radio 3 Sync"
"Radio 4 Sync"
"Radio 1 Tripped"
"Radio 2 Tripped"

2 个答案:

答案 0 :(得分:6)

如果您提供示例输入(我不知道snmpwalk的输出是什么样的),我会对此更有信心。但据我所知,你期望数组只在换行符处分割文本,而不是在空格处。默认情况下,bash在空格,制表符和换行符处拆分。要更改该行为,您可以修改IFS I 输入 F ield S eparator)的值:

OLDIFS="$IFS"
IFS=$'\n'      # newlines are the only separator
IN=($(my_command ...))
IFS="$OLDIFS"

额外的两行保存并恢复IFS的值,以防脚本的其他部分依赖它。

(顺便说一句,如果你谷歌“bash数组换行符”,你会发现一些解释这一点。)

答案 1 :(得分:0)

尝试这样的事情:

mlm@matt-mmf-macbook.local:~
$ a=( "data1 data2" "data3 data4" )

mlm@matt-mmf-macbook.local:~
$ echo "${a[0]}"
data1 data2

mlm@matt-mmf-macbook.local:~
$ echo "${a[1]}"
data3 data4