在Bash后台运行的while循环中如何导出一个变量?

huangapple go评论59阅读模式
英文:

How can I export a variable from whithin a while loop runing in the background in bash?

问题

我编写了一个 bash 脚本,每隔 10 分钟使用 yay 软件包管理器在我的 Arch Linux 系统上检查系统更新。出于其他目的,我需要在后台运行 while 循环,并导出 `updates` 变量以在同一脚本中的其他地方使用。一切都正常工作,除了变量没有被导出。

```bash
#!/bin/sh

updates=''

while true; do
  updates=$(ping -q -c 1 -W 1 ping.eu > /dev/null && yay -Qu | wc -l)
  export updates
  sleep 600
done &

echo $updates

<details>
<summary>英文:</summary>

I have written a bash script that checks for system updates every 10 minutes in my Arch Linux system using the yay package manager. For other purposes I need to run the while loop in the background and to export the `updates` variable to use it elsewhere within the same script. Everything works, except that the variable is not exported.

#!/bin/sh

updates=''

while true; do
updates=$(ping -q -c 1 -W 1 ping.eu > /dev/null && yay -Qu | wc -l)
export updates
sleep 600
done &

echo $updates


</details>


# 答案1
**得分**: 2

Processes can't directly read variables set in child processes, so you need a different way to communicate the `updates` value. One option is to use a temporary file:

```shell
#!/bin/sh

printf '' > updates.txt

while true; do
    ping -q -c 1 -W 1 ping.eu > /dev/null && yay -Qu | wc -l > updates.txt
    sleep 600
done &

# [Do stuff]
# ...

updates=$(cat updates.txt)
printf '%s\n' "$updates"
英文:

Processes can't directly read variables set in child processes, so you need a different way to communicate the updates value. One option is to use a temporary file:

#!/bin/sh

printf &#39;&#39; &gt;updates.txt

while true; do
    ping -q -c 1 -W 1 ping.eu &gt; /dev/null &amp;&amp; yay -Qu | wc -l &gt;updates.txt
    sleep 600
done &amp;

# [Do stuff]
# ...

updates=$(cat updates.txt)
printf &#39;%s\n&#39; &quot;$updates&quot;

huangapple
  • 本文由 发表于 2023年3月8日 18:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定