Bash字符串数组

时间:2016-02-25 11:43:35

标签: arrays bash snmp

我有一个bash脚本,它收集snmp信息并搜索关键短语以提醒。

我使用snmp命令从网络设备输出日志,这是代码和原始输出的示例 -

/usr/bin/snmpwalk -v 2c -c public $HOST .1.3.6.1.3.94.1.11.1.9.32.128.0.192.255

SNMPv2-SMI::experimental.94.1.11.1.9.32.128.0.192.255.27.228.239.0.0.0.0.0.0.0.0.251 = STRING: "Host link down. (port: 1)"
SNMPv2-SMI::experimental.94.1.11.1.9.32.128.0.192.255.27.228.239.0.0.0.0.0.0.0.0.252 = STRING: "Host link up. (port: 1, speed: 8 Gbps, number of loop ID(s):"
SNMPv2-SMI::experimental.94.1.11.1.9.32.128.0.192.255.27.228.239.0.0.0.0.0.0.0.0.253 = STRING: "A scrub-vdisk job was started. (vdisk: test, SN: 00c0ff1bf86d0000a6c09c5600000000)"
SNMPv2-SMI::experimental.94.1.11.1.9.32.128.0.192.255.27.228.239.0.0.0.0.0.0.0.0.254 = STRING: "A scrub-vdisk job completed. No errors were found. (vdisk: test, SN: 00c0ff1bf86d0000a6c09c5600000000)"
SNMPv2-SMI::experimental.94.1.11.1.9.32.128.0.192.255.27.228.239.0.0.0.0.0.0.0.0.255 = STRING: "Host link down. (port: 1)"

在我的bash脚本中,我从中创建一个数组并在开始时删除bumph -

declare -a LOG=($(/usr/bin/snmpwalk -v 2c -c public $HOST $OID | cut -d" " -f 4-))

这会创建 -

"Host link down. (port: 1)"
"Host link up. (port: 1, speed: 8 Gbps, number of loop ID(s):"
"A scrub-vdisk job was started. (vdisk: test, SN: 00c0ff1bf86d0000a6c09c5600000000)"
"A scrub-vdisk job completed. No errors were found. (vdisk: test, SN: 00c0ff1bf86d0000a6c09c5600000000)"
"Host link down. (port: 1)"

我的问题是这个数组将每个单词视为一个单独的条目,所以我的实际输出是这个 -

"Host 
link 
down. 
(port: 
1)"

因此,每当我搜索单个单词时,它都可以正常工作,但是当我搜索短语时,它会中断。

理想情况下,我希望它能将每行文本存储为数组中的自己的条目,如下所示 -

declare -a LOG=('"Host link down. (port: 1)"' '"Host link up. (port: 1, speed: 8 Gbps, number of loop ID(s):"') etc

我只是不确定如何操纵原始声明行来执行此操作...

这是我的所有代码 -

HOST="10.10.10.10"
OID=".1.3.6.1.3.94.1.11.1.9.32.128.0.192.255"
declare -a CRITICAL=('errors' 'An event was reported by a disk drive')

declare -a LOG=($(/usr/bin/snmpwalk -v 2c -c public $HOST $OID | cut -d" " -f 4-))

for RESULT in `echo ${LOG[*]}`
    do
    for WORD in `echo ${CRITICAL[*]}`
        do
            case "$RESULT" in
                *$WORD*)
                    OUTPUT+="$RESULT -CRITICAL "
                    ;;
                *)
                    OUTPUT+="$RESULT "
            esac    

        done
done

1 个答案:

答案 0 :(得分:2)

如果您将IFS(internal field separator)变量设置为\n,它应该达到您想要的效果。

IFS=$'\n' declare -a LOG=($(/usr/bin/snmpwalk -v 2c -c public $HOST $OID | cut -d" " -f 4-))

您在迭代结果的方式上也存在问题。尝试以下操作,这样就不会将各行分成单词(*运算符会这样做)。

for RESULT in "${LOG[@]}"
    do
    for WORD in "${CRITICAL[@]}"
        do