How to assign the output of a background job into a bash variable?

这一生的挚爱 提交于 2021-02-07 09:51:47

问题


I would like to run a background job in bash and assign its result to a variable.

I prefer not to use temporary files and I would love to run multiple similar background tasks at the same time.

root@root:/# var=$(echo "hello world")
root@root:/# echo $var
hello world
root@root:/# back_var=$(sleep 2s && echo "hello world back") &
[1] 2102
root@root:/# wait
root@root:/#jobs
[1]+  Done                    back_var=$(sleep 2s && echo "hello world back")
root@root:/# echo $back_var

root@root:/# 

I prefer not to use gnu-parallel or temp files.

To be even clearer that's not a trivial question IMHO:

root@root:/# back_var_1=$(sleep 4s && echo "Don't waste my time" &) &
[1] 26584
root@root:/# wait
[1]+  Done                    back_var_1=$(sleep 4s && echo "Don't waste my time" &)
root@root:/# echo $back_var_1

root@root:/#

回答1:


With named pipes it's possible. However, I don't know whether it'll be considered as a temp file :

 $ mkfifo pipo
 $ sleep 4s && echo "this is not fair" > pipo & 
 [1] 25356

 $ back_var=$(cat pipo)
 [1]+  Done                    sleep 4s && echo "this is not fair" > pipo

 $ echo $back_var
 this is not fair

Hope it helps.



来源:https://stackoverflow.com/questions/37854393/how-to-assign-the-output-of-a-background-job-into-a-bash-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!