1

我正在尝试编写一个脚本来扫描蓝牙设备并跟踪设备的名称、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="," 读取 -r 时间 mac 名称
    做
            #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"
            如果 [[ !${first_seen[$mac]} ]]; 然后
                    first_seen["$mac"]="$time"
                    echo "先设置"
            菲

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

这解决了问题。

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

很抱歉在提出问题的早期就成为了一次搜索。

谢谢你的时间。

4

1 回答 1

2

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

于 2013-02-28T17:49:12.880 回答