I am running valgrind to shake out bugs in my program. Valgrind's memcheck prints to stderr. What I want to do is a modification to this:

valgrind --tool=memcheck ./a.out >output 2>grindout

But, I also want valgrind output to display on screen. So program's output all goes to file. Valgrind output is placed in grindout and displayed to screen. How do I do so?



You're looking for the tee command. Unfortunately there's some trickery regarding redirecting stderr and stdout. The following should work:

valgrind --tool=memcheck ./a.out 3>&1 2>&3 >output | tee grindout

This redirects standard output to output, moves standard error to a new file descriptor 3, which points to stdout. tee takes this stdout-ified stderr and prints it both to your screen and to gridnout.

  • Thanks, but I want stderr to go to screen and to file. But stdout to go to file and NOT to screen. – Badministrator Sep 14 '12 at 13:17
  • @Badministrator I've updated my answer to get that behavior. It's unexpectedly complicated (see this Stackoverflow question). – Jjed Sep 14 '12 at 13:40

Use tee for this, but you need to play some tricks with the stdout / stderr.

valgrind --tool=memcheck ./a.out 2>&1 > output | tee grindout

Explanation: 2>&1 sends stderr to stdout, and the regular stdout gets send to file output. The tee program passes on the stdin, but it also saves it to file grindout.


I had this same issue. The problem was caused by buffering. You can read more about there here: http://mywiki.wooledge.org/BashFAQ/009

This is the solution that worked for me:

stdbuf -o0 valgrind -v --tool=memcheck stdbuf -o0 ./a.out  2>&1 | stdbuf -o0 tee grindout

the 'stdbuf -o0' placed in front of each of the three programs that get executed causes them to turn off buffering.

The problem was never the the output wasn't being generated, nor was the problem that it wasn't going to the right place. The problem was that it wasn't getting there at the right time ( due to buffering )

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.