Michel Müller
Michel Müller

Reputation: 5705

Coloured terminal output & logging

I use tput setaf [colornum] && echo [text] && tput sgr0 in a Makefile to highlight some parts of the output, which is nice to find stuff in the output quicker. My problem is that when I want to log the output, for example using make > my_log.txt, the file has all these control characters in front of the lines that were previously colored. Is there an easy way to have both - formatted output in the terminal as well as the ability to store it as a log? I'd prefer a solution where stdout remains loggable instead of handling the logfile internally in the script / makefile.

Upvotes: 0

Views: 712

Answers (1)

MadScientist
MadScientist

Reputation: 101081

You need to test whether stdout is a terminal, before you print your magical characters. If it's not a terminal you shouldn't print them. You can test this with [ -t 1 ] (1 is the file descriptor of stdout). So:

[ -t 1 ] && tput setaf [colornum]; echo [text]; [ -t 1 ] && tput sgr0; true

EDIT

I should add one thing: starting with GNU make 4.1, you can also test the make variable MAKE_TERMOUT and if it's set then you should assume you are writing to a terminal, even if -t says no. This is because these versions of make support a new feature, --output-sync, which ensures that output from parallel jobs is not intermixed even during parallel builds. In order to do this, though, make has to capture the output temporarily then display it in a serial manner which means that to shell processes it never looks like stdout is a terminal. If you're using that version of GNU make you can use something like:

$(if $(MAKE_TERMOUT),tput setaf [colornum];) echo [text] $(if $(MAKE_TERMOUT),; tput sgr0)

Upvotes: 2

Related Questions