Search code examples
makefilegnu-makegnome-terminalansi-colors

Print bold or colored text from Makefile rule


I'm trying to print bold text from the following Makefile :

printf-bold-1:
    @printf "normal text - \e[1mbold text\e[0m"

But, escape sequences are printed as-is, so when running make printf-bold-1, I got :

normal text - \e[1mbold text\e[0m

Instead of expected :

normal text - bold text

It's weird because I can print bold text from my terminal : running directly command printf "normal text - \e[1mbold text\e[0m" produces, as expected :

normal text - bold text

In the Makefile, I tried to use @echo or echo instead of @printf, or print \x1b instead of \e, but without success.

Here are some variables describing my environment (Linux with standard Gnome terminal), if that can help :

COLORTERM=gnome-terminal
TERM=xterm-256color

Note also that on some colleagues laptops (Mac), bold text is printed correctly.

What is the portable way, working on every environment, to print bold or colored text from a Makefile rule?


Solution

  • You should use the usual tput program for producing the correct escape sequences for the actual terminal, rather than hard-coding specific strings (that look ugly in an Emacs compilation buffer, for example):

    printf-bold-1:
        @printf "normal text - `tput bold`bold text`tput sgr0`"
    
    .PHONY: printf-bold-1
    

    Of course, you may store the result into a Make variable, to reduce the number of subshells:

    bold := $(shell tput bold)
    sgr0 := $(shell tput sgr0)
    
    printf-bold-1:
        @printf 'normal text - $(bold)bold text$(sgr0)'
    
    .PHONY: printf-bold-1
    

    You might even consider defining a function for styling output:

    text-style = $(shell tput $1)$2$(shell tput sgr0)
    
    printf-bold-1:
        @printf %s\\n 'normal text - $(call text-style,bold,bold text)'
        @echo '$(call text-style,setaf 1,red text)'
    
    .PHONY: printf-bold-1