【问题标题】:Storing bash associate-array's values in while loop在while循环中存储bash关联数组值
【发布时间】:2013-02-18 18:24:26
【问题描述】:

我正在尝试编写一个脚本来扫描蓝牙设备并跟踪设备的名称、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]}" 完成

这就解决了问题。

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

很抱歉在提出问题的时候就被搜索了一个。

感谢您的宝贵时间。

【问题讨论】:

    标签: bash associative-array


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 2015-06-13
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2011-07-12
      • 2016-06-26
      相关资源
      最近更新 更多