Echoing output to file while seeing it in console in the same time

2

So I echo output of my programs ran in terminal by command 2>&1 >> /path/toFile.txt

It creates few limitations that I want to overcome:

  1. It "freezes" and gives no output in terminal - only way to see actual output is to open output file
  2. Opening output file is not giving live results. It gives results from time of opening that file

How to echo output to a file and be able to:

a) see live changes in that file (separate program would be needed I assume)

or

b) output to file and see that output in terminal in the same time

Szymon Toda

Posted 2013-12-28T08:51:21.973

Reputation: 1 239

Question was closed 2015-11-30T19:07:52.183

1There is a problem with the command - more details please. – suspectus – 2013-12-28T09:15:15.007

Answers

9

For a) There is a utility called "tail" that shows the last few lines of a file and optionally monitors a file for new lines added to the end:

$ tail -f /path/toFile.txt

The less pager also has the ability to follow changes, pressing shift-F causes it to enter a mode much like tail -f, with the advantage that a single press of ctrl-c will get you back into the normal file viewing mode, so that you can scroll backwards through the file or search through it without closing it.

For b) There is a standard utility called tee for just this purpose (http://www.gnu.org/software/coreutils/manual/coreutils.html#tee-invocation)

You'll probably want something like the following:

command 2>&1 | tee -a /path/toFile.txt | less

The | less at the end is obviously optional, but be aware that if you include it, closing down less will probably also close down the command you are running.

As an aside, if this is to be a long running process, strongly consider either running it under nohup or running it inside screen, so that it survives a logout.

Stephanie

Posted 2013-12-28T08:51:21.973

Reputation: 1 778

What is it 'The less pager' – Szymon Toda – 2013-12-29T12:53:52.173

less is a "pager" (a program that lets you scroll through files on the terminal), a drop in replacement for the traditional "more" pager with the ability to go backwards as well as forwards. (http://en.wikipedia.org/wiki/Less_%28Unix%29)

– Stephanie – 2013-12-29T15:06:48.817

3

This sounds like a job for tee. The output will simultaneously be written to the terminal and to the file.

command 2>&1 | tee -a /path/toFile.txt

dbenham

Posted 2013-12-28T08:51:21.973

Reputation: 9 212

// , Tested this in a SystemD unit file, and it doesn't work. – Nathan Basanese – 2018-10-26T00:16:55.740

1Since the command in the question appends to a file, it's good to know that this command will overwrite the file, but you can specify -a to append instead. – brm – 2013-12-29T15:12:22.880

1@brm - Good point, I didn't notice the >> in the original question. Answer has been edited to include -a – dbenham – 2013-12-29T15:24:18.813