I have a command in a bash script which I want to capture the output of and then send it to the background. How do I get this done?

The following doesn't seem to work (it keeps blocking and outputs nothing)

result=`node /var/www/animekyun/node/node_modules/peerflix/app.js $torrent -r -q &`

This doesn't seem to work. The output is 2 lines btw which I want to store in a variable as an array. This way I can use the output in the rest of my script.


What you want (as I understand it) is impossible. You cannot collect the output (with command substitution) and then run the program in the background. for the simple reason that the output is collected over the whole life time of a process. A process may live long after it has stopped producing output but the shell cannot know that.

You have to redirect the output to a file and have to check somehow (that is application-specific) when the output is complete (if you do not want to wait for the process to finish).

node /var/www/animekyun/node/node_modules/peerflix/app.js $torrent -r -q >file &
  • Correct explanation, but your solution doesn't do anything sensible: it stops reading file whenever it feels like it, regardless of the amount of data that's been written to it. Nov 19 '14 at 0:47
  • 2
    The text prior to the code mentions that it is up to the user to replace [...] with something that determines when it is safe to read from file, whether it be calling wait to block until the process exits, or waiting until file has some minimum length, or something else.
    – chepner
    Nov 19 '14 at 4:04
  • Since the output is just 2 lines, I can try to read the file and check if it has 2 lines. If that's the case I can continue doing my thing
    – Ortix92
    Nov 19 '14 at 8:21

Untested, but this might work with a FIFO:

mkfifo $filename
node /var/.../app.js $torrent -r -q >$filename &
{ read first_line; read second_line; } <$filename

# do something with "$first_line" and "$second_line"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.