如何将后台作业的输出分配到bash变量中?

时间:2021-07-14 15:44:22

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

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

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.

我不喜欢使用gnu-parallel或temp文件。

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 个解决方案

#1


2  

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.

希望它可以帮助。

#1


2  

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.

希望它可以帮助。