4

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:/#
0x90
  • 39,472
  • 36
  • 165
  • 245
  • I don't understand why you are catching `sleep`. Why don't you just say `sleep 2 && var=$(echo "hello world") &`? – fedorqui Jun 16 '16 at 09:05
  • @fedorqui, it's just a toy mode example in order to demonstrate what I want to achieve. Consider a case where the in parenthesis is an async operation (IO) with long execution time command. – 0x90 Jun 16 '16 at 09:09
  • 1
    OK, I see. Probably worth reading [Bash: Capture output of command run in background](http://stackoverflow.com/q/20017805/1983854). I haven't gone through it thoroughly, but may contain juicy info. – fedorqui Jun 16 '16 at 09:11
  • @fedorqui, The thread you were referring to isn't what I am looking for AFAICS – 0x90 Jun 16 '16 at 13:42
  • 1
    @0x90 : I've got my mistake. Have you considered using named pipes ? – blackSmith Jun 16 '16 at 14:01
  • 1
    Uh, don't be `root`, especially if you don't know exactly what you are doing. – tripleee Jun 21 '16 at 05:12

1 Answers1

3

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.

blackSmith
  • 3,054
  • 1
  • 20
  • 37
  • It's a nice idea. Fifos are blocking too, so one can use it as a sync mechanism as well. – 0x90 Jun 21 '16 at 06:47