【问题标题】:Setting environment variables with background processes running in parallel使用并行运行的后台进程设置环境变量
【发布时间】:2020-10-26 16:08:46
【问题描述】:

我有一个文件需要 1 分钟才能获取。因此,在我需要获取的那个文件中,我创建了函数,然后使用 & 并行运行它们。从子进程导出的变量在当前环境中不可用。是否有解决此问题的解决方案或技巧?谢谢。 示例:

#!/bin/bash
function getCNAME() {
 curl ...... grep
 export CNAME
} 

function getBNAME() {
  curl ...... grep
  export BNAME 
}
getCNAME &
getBNAME &

然后我有一个主文件,它在上面的代码中调用源命令并尝试使用变量 BNAME 和 CNAME。但又是做不到。如果我删除 & 它确实可以访问这些变量,但需要很长时间才能获取文件。

【问题讨论】:

  • 您能否使用要获取的文件的最小示例以及如何调用它来展示您正在做什么?我不确定我理解你在哪里调用你的函数。
  • #!bin/bash function getCNAME() { curl ...... grep export CNAME } function getBNAME() { curl ...... grep export BNAME } CNAME & BNAME &
  • 你应该 edit 带有该信息的问题,cmets 更难阅读且短暂。
  • 子shell不能导出或传递变量给它的父shell。
  • 如果你来源它,为什么文件有一个shebang? shebang 是执行脚本所必需的。但是,如果您获取文件,那将毫无用处。它会影响环境。如果执行脚本,任何export 定义对调用进程都没有影响。当然,您必须等待后台作业。只需在末尾添加wait。

标签: bash environment-variables child-process


【解决方案1】:

您不能在子 shell 中使用 export 并期望父 shell 可以访问结果变量。考虑改用进程替换:

#!/bin/bash
# note that if you're sourcing this, as you should be, the shebang will be ignored.
# ...hopefully it's just there for your editor's syntax highlighting.

rc=0
orig_pipefail_setting=$(shopt -p pipefail)
shopt -s pipefail # make sure if either curl _or_ grep fails the entire pipeline does too

# start both processes in the background, with their stdout on two different FDs
exec 4< <(curl ... | grep ... && printf '\0')
exec 5< <(curl ... | grep ... && printf '\0')

# read from those FDs into variables in the current shell
IFS= read -r -d '' BNAME <&4 || { (( rc |= $? )); echo "Error reading BNAME" >&2; }
IFS= read -r -d '' CNAME <&5 || { (( rc |= $? )); echo "Error reading CNAME" >&2; }

exec 4<&- 5<&-      # close those file descriptors now that we're done with them
export BNAME CNAME  # note that you probably don't actually need to export these
eval "$orig_pipefail_setting"  # turn pipefail back off, if it wasn't on when we started
return "$rc"        # ...return with an exit status reflecting whether we had any errors

这样文件描述符 4 和 5 将分别附加到运行 curl 并将其输出提供给 grep 的 shell 管道;在我们尝试读取之前,它们都在后台启动,因此它们都在同时运行。

【讨论】:

    【解决方案2】:

    你确定最后两行不应该是:

    getCNAME
    getBNAME
    

    编辑 - OP 已修复此问题,它曾经读取:

    CNAME
    BNAME
    

    如果您正在获取脚本 (. /my/script),它不是子进程,并且它的变量将在当前 shell 中可用。你甚至不需要导出。

    如果你正常执行一个脚本,它是一个子进程,你不能在父shell中设置变量。

    我知道的将数据传输到父 shell 的唯一方法是通过文件。

    变量应该可用。 检查脚本中的错误:
    确保您没有将 local 用于函数中的变量。
    在源脚本的底部执行echo "$CNAME",以测试功能是否真正起作用。

    编辑

    我做了更多调查。这就是问题所在:&amp; 将命令/函数放入子 shell。这就是变量不可用的原因。在 sourced 脚本中,如果没有 &amp;,它会是。

    来自man bash:

    如果一个命令被控制操作符 & 终止,shell 在子shell 的后台执行命令。外壳可以 不等待命令完成,返回状态为 0。 这些被称为异步命令。

    【讨论】:

    • OP 正在尝试并行运行这两个进程,因为它们很慢。不对它们进行后台处理可以解决问题,但会破坏预期的性能改进。
    猜你喜欢
    • 2012-10-17
    • 1970-01-01
    • 2021-12-23
    • 2017-06-06
    • 2020-04-06
    • 2020-02-22
    • 2019-02-07
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多