在while循环中存储bash关联数组值

时间:2013-02-18 18:24:26

标签: bash associative-array

我正在尝试编写一个扫描蓝牙设备的脚本,并跟踪设备首次和最后一次显示的名称,mac和时间。我遇到了将数据存储到扫描之间的相关数组中的问题。

在第二次扫描中,我会想到阵列会被填充,但它们不会。所以我第一次看到设备时无法知道。我很确定问题是数据存储到数组的本地版本而不是全局但我不确定如何解决它。

这是我第一次尝试除了非常基本的shell脚本以外的任何内容,因此对脚本任何部分的任何建议都将受到赞赏。我一直在谷歌上搜索问题,毫无疑问我做的事情不是100%正确或有效。




    #!/bin/bash

    declare -A bt_name
    declare -A last_seen
    declare -A first_seen

    while [ 1 ] ; do
            echo ""> ../data/bt_host.log
            date=$(date +%s)
            hcitool -i $1 scan| grep -v Scanning | sed "s/\t/$date, /" | sed "s/\t/, /" | while IFS="," read -r time mac name
            do
                    #debug to see if array values are there from last loop
                    echo "PREFILL-mac: $mac first: ${first_seen[$mac]} name: ${bt_name[$mac]} last: ${last_seen[$mac]}"

                    #populate arrays
                    bt_name["$mac"]="$name"
                    last_seen["$mac"]="$time"

                    #test if have seen this device before or not
                    if [[ ! ${first_seen[$mac]} ]]; then
                            first_seen["$mac"]="$time"
                            echo "Setting first"
                    fi

                    #resulting array values
                    echo "POSTFILL-mac: $mac first: ${first_seen[$mac]} name: ${bt_name[$mac]} last: ${last_seen[$mac]}"

            done
            sleep 10
    done

感谢您的帮助。

更新: 发现问题(我问之后粗糙的问题)。这是我的while循环中进程替换的问题。

我把它改成了


    while IFS="," read -r time mac name
    do
            #echo "$mac, $name, $time"
            echo "PRE-mac: $mac first: ${first_seen[$mac]} name: ${bt_name[$mac]} last: ${last_seen[$mac]}"
            bt_name["$mac"]="$name"
            last_seen["$mac"]="$time"
            if [[ ! ${first_seen[$mac]} ]]; then
                    first_seen["$mac"]="$time"
                    echo "Setting first"
            fi

            echo "POST-mac: $mac first: ${first_seen[$mac]} name: ${bt_name[$mac]} last: ${last_seen[$mac]}"
    done 

这解决了这个问题。

如果人们有任何其他改进/建议,他们将不胜感激。

很抱歉在提问时尽早搜索。

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

在bash 4.2中,您可以要求在当前shell中运行最后一个命令:shopt -s lastpipe