Terminal Color Support in Makefiles
Jul 21st, 2015

colors frustrating make project management terminal
Annual hours saved: 5

I just spent a good 20 minutes trying to figure out how to have a makefile conditionally color its output depending on the current terminal’s level of color support. Long story short, there were a number of make idiosyncrasies that I wasn’t expecting / had forgotten about. So, for future reference, here’s a quick recap:

  • Conditional syntax requires parentheses when comparing evaluated (i.e. $(...)) values
  • Terminal commands are invoked using the $(shell ...) function
  • The default shell is sh, not bash, so echo evaluates escapes by default
  • During assignment, := evaluates immediately, while = does not
  • As in most terminals, un-assigned variables evaluate without error as empty strings

Here is the important excerpt from my eventual working makefile:
(I also updated Makefile (Git edition))

COLORS:=$(shell tput colors 2> /dev/null)
ifeq ($(COLORS), 256)
    COLOR_RESET=\033[0;39;49m
    COLOR_GREN=\033[38;5;118m
    COLOR_BLUE=\033[38;5;81m
    COLOR_RED=\033[38;5;161m
    COLOR_PURP=\033[38;5;135m
    COLOR_ORNG=\033[38;5;208m
    COLOR_YELO=\033[38;5;227m
    COLOR_GRAY=\033[38;5;245m
    COLOR_WHIT=\033[38;5;15m
else ifeq ($(COLORS), 16)
    COLOR_RESET=\033[0;39;49m
    COLOR_GREN=\033[0;32m
    COLOR_BLUE=\033[0;34m
    COLOR_RED=\033[0;31m
    COLOR_PURP=\033[0;35m
    COLOR_ORNG=\033[1;31m
    COLOR_YELO=\033[0;33m
    COLOR_GRAY=\033[1;30m
    COLOR_WHIT=\033[1;37m
endif

You can now use directives like the following:

test:
    @echo "[ $(COLOR_GREN)OK$(COLOR_RESET) ]"
    @echo "[ $(COLOR_RED)Error$(COLOR_RESET) ]"
Your E-Sheep:

( change )

Recent Posts:

10/14 - ADHOC Changelog
8/19 - And now… random puppies!
8/3 - Check Braces
7/23 - Make Limits Java Heap Size on 32-bit Linux
7/21 - Terminal Color Support in Makefiles

Search
Top Tags:

aaaaargh! algorithms automatic awesome colors config development environment documentation frustrating java linux make parsing project management random syntax-highlighting terminal types

Random Quote:

A-hyuck!
Goofy

Powered By:
License:

2017 - Creative Commons 3.0