brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: tput setaf colours script output in the terminal without hard coded escapes

Terminal
~/tips/tip-terminal-tput-setaf-colours

red=$(tput setaf 1); green=$(tput setaf 2)

Adds colour to script messages in a way that stays quiet on dumb terminals.

Many scripts print colours with codes like \033[31m pasted everywhere. tput asks the terminal database for the right code instead.

tput setaf N prints the code that sets the foreground colour to colour N for the terminal in $TERM, and tput sgr0 resets all attributes. I’d store them once at the top of a script:

red=$(tput setaf 1); green=$(tput setaf 2)
bold=$(tput bold); reset=$(tput sgr0)

printf '%sOK%s backup finished\n' "$green" "$reset"
printf '%s%sFAILED%s disk not mounted\n' "$bold" "$red" "$reset"

The basic colours are 0 black, 1 red, 2 green, 3 yellow, 4 blue, 5 magenta, 6 cyan and 7 white. tput colors tells you how many the terminal claims to support, 8 or 256 in most cases.

The nice part comes when output goes somewhere that can’t show colour. With TERM=dumb there is no code to print, tput outputs nothing and exits non-zero, and your messages stay plain text.

It doesn’t check whether output goes to a pipe or a log file, though. To keep escape codes out of backup.log, only set the variables when [ -t 1 ] says standard output is a terminal, and leave them empty otherwise.

Further reading: tput(1) Linux manual page, tput man page (macOS)

More Terminal tips ioreg -rn AppleSmartBattery | grep CycleCount Terminal can save your windows and tabs as a window group Export a Terminal profile to a .terminal file and import it on another Mac mc hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}' All Terminal tips (116) All topics

Link