What I'd like to do is to run a command, write all output to a file and display the first n lines.

in this example n=10

One solution I don't really like is:

./program > tempfile ; cat tempfile >> thefile ; head -n 10 tempfile

What I tried is

./program | tee -a thefile | head -n 10

However here the problem is, that ./program is terminated prematurely

Is there any trick without creating an intermediate temp file. (like a head command just displaying the first n lines, but continuing to read the rest silently)

One way to reproduce the issue with the pipeline and head is:

n=0 ; while [[ $n -lt 200 ]] ; do echo ======================== $n ; n=$((n + 1)) ; done | tee -a toto | head -n 3 ; echo "-" ; tail -n 200 toto

In fact for me the last line of file toto is random and varies but is almost never line 199.

  • This answer might be of interest. Suggests that ./program 2>&1 | tee -a thefile | head -n 10 should work. – Smock Dec 3 at 17:04
  • @Smock Just tried it out, even here program will be terminated prematurely. :-( – gelonida Dec 3 at 18:17
  • Are you saying that it gets terminated early because you are piping it? – Smock Dec 4 at 11:20
  • Yes exactly, this seems to be the case. Just try following in a command line and you'll see: cat | head -n 3 and enter a few lines. Funny that I use head for ages and I never noticed as in the use cases so far it didn't matter that the program terminated prematurly. My suggested sed answer continues reading and doesn't terminate but it's not the most elegant – gelonida Dec 4 at 11:52
  • Ahhh - does the program read user input? I managed to replicate when I setup a script to read 10 vars in, and set head to show 5, it quit after 5 inputs. (it also mangled what got show on the terminal and what was recorded in the text file).# – Smock Dec 4 at 12:10

Hmm, answering my own question.

./program | tee -a thefile | sed -n "1,${n}p"

But perhaps there is something better?

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.