3

How can I continuously output the results of a long running shell command, as the output becomes available?

Currently I need to do this (which I can only see after command has finished)

puts long_running_shell_command

What I want to do conceptually is

puts_immediately long_running_shell_command

1
  • how are you executing your shell command? the execution style you choose dictates whether you'll get a data stream (which gets continuously output) or buffered data (which is printed all at once). Commented Apr 4, 2017 at 13:17

2 Answers 2

4

Redirect the output to STDOUT:

# waits a second, prints the current directory's contents, waits 5 seconds
system('sleep 1; ls; sleep 5', out: STDOUT)
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and effective.
2

My favorite way to work with shell commands is like so:

Open3.popen3 "shellcommand --args --more-args" do |stdin, stdout, stderr, thread|
  while line = stdout.gets
    puts line
  end
end

The command gives you input, output and error streams. You can call stdout.gets to get the next line of output (my favorite), or stdout.getc for the next character, if you really want immediacy. The function waits until input is available and then returns nil when the command completes, so a common technique is to wrap the command in a while-loop and have a set of commands repeatedly execute until the command completes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.