英文:
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 '' >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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论