[英]Setting environment variables with background processes running in parallel
我有一個需要 1 分鍾才能獲取的文件。 因此,在我需要獲取的文件中,我創建了函數,然后使用 & 並行運行它們。 從子進程導出的變量在當前環境中不可用。 是否有解決此問題的解決方案或技巧? 謝謝。 樣本:
#!/bin/bash
function getCNAME() {
curl ...... grep
export CNAME
}
function getBNAME() {
curl ...... grep
export BNAME
}
getCNAME &
getBNAME &
然后我有一個主文件,它在上面的代碼中調用 source 命令並嘗試使用變量 BNAME 和 CNAME。 卻無能為力。 如果我刪除 & 它確實可以訪問這些變量,但需要很長時間來獲取文件。
您不能在子 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 管道; 在我們嘗試從中讀取之前,它們都在后台啟動,因此它們同時運行。
你確定最后兩行不應該是:
getCNAME
getBNAME
編輯 - OP 已修復此問題,它用於讀取:
CNAME
BNAME
如果您正在獲取腳本 ( . /my/script
),則它不是子進程,並且其變量將在當前 shell 中可用。 你甚至不需要導出。
如果正常執行腳本,則是子進程,不能在父shell中設置變量。
我所知道的將數據傳輸到父 shell 的唯一方法是通過文件。
變量應該是可用的。 檢查腳本中的錯誤:
確保您沒有對函數中的變量使用local
。
在源腳本的底部執行echo "$CNAME"
,以測試函數是否實際工作。
編輯
我又做了一點調查。 這是問題所在: &
將命令/函數放在 subshell 中。 這就是變量不可用的原因。 在源腳本中,如果沒有&
,它將是。
從man bash
:
如果命令由控制運算符 & 終止,shell 將在子 shell 的后台執行該命令。 shell 不會等待命令完成,返回狀態為 0。這些被稱為異步命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.