如何将后台作业的输出分配到bash变量中? [英] How to assign the output of a background job into a bash variable?

查看:60
本文介绍了如何将后台作业的输出分配到bash变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在bash中运行后台作业,并将其结果分配给变量.

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:/# 

我不想使用gnu-parallel或temp文件.

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:/#

推荐答案

使用命名管道是可能的.但是,我不知道是否将其视为临时文件:

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

希望有帮助.

这篇关于如何将后台作业的输出分配到bash变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆