在 BASH 中使用带有函数的等待命令后不保留变量

Variables are not retained after using wait command with a function in BASH

我必须记录来自各种传感器的测量值,其中一些需要相当长的时间。我想同时获取传感器的读数以节省时间。

我有一个函数,foo,它读取一些传感器并将值保存为变量,例如名为 bar.

的变量

我正在使用 wait 命令暂停脚本,直到 foo 函数完成,然后再通过 HTTP get 将所有测量值发送到服务器进行记录。

#!/bin/bash

function foo {
    bar=$(command for reading sensor here)
    echo "bar is $bar"
}

foo & #this is to run the foo function as a background process.

temperature=$(command for measuring temperature here)
humidity=$(command for measuring humidity here)

wait %1 #this should pause the script until the function foo is complete.
echo "function foo has finished. bar is $bar"

curl -X GET -G (URL to server) -d bar=$bar -d temperature=$temperature -d humidity=$humidity

当我运行脚本时,输出如下:

bar is 1234

function foo has finished. bar is

注意这个应该说“function foo has finished. bar is 1234”。

...如果我在脚本开头添加 set -x,curl 命令(在脚本末尾)最终看起来像这样:

curl -X GET -G (URL to server) -d bar= -d temperature=21.5-d humidity=65

再次注意 bar 变量为空。

如果我有没有 wait 命令的相同脚本(和 运行 后面没有&符号的函数),该函数正确设置 bar 变量,生成的 curl 命令就完成了。但是,当我像上面那样使用 wait 命令时,foo 函数中的变量一旦函数完成就会丢失。

是否有一些方法可以保留由函数 foo 设置的这些变量?

只是在这里总结 Barmar 的评论,以便将其标记为答案...

问题是后台的 运行ning 函数在子 shell 中是 运行,而不是与主脚本相同的 shell 运行ning 中,而在子shell 中设置的变量永远不会传递到主shell 中(其中脚本本身是运行ning)。

一个可能的解决方案是将变量写入一个文件,然后 - 在等待命令之后 - 再次从这些文件中读取变量。