JagaScript

Logo
3 min read

How to Show Colored Text in Terminal?

March 03, 2020
tags: cli, terminal

There are many things that we see and use every day but rarely we stop and think “how does it work?”, other times we ask ourselves that question but dismiss it because we suppose that the answer is probably super complicated.

This was the case for me about wondering how terminals show different colors, in my mind, it has always been something extremely complicated until I realized it’s quite simple and easy.

For years I’ve been using tools that show colored output and from time to time I used them too, always relying on libraries such a chalk in Node.js

This until one day, I wanted to print some errors messages in red in a simple script and wanted to avoid using a library for such a simple case, that day I understand the basics of colors and another formatting in terminal output

all required is to print some special sequence of characters called ANSI escape and the text after that will have the specific color or background or text style

these are standardized and interpreted by almost any terminal emulator

for example the Espace code \x1b[32m will start printing in green while \x1b[0m is the reset Espace and will reset the next text to normal

try to print this in you terminal

echo "I'm normal \x1b[32m I will be green \x1b[47m I will have white background \x1b[4m I will be underscored \x1b[0m, not I'm back to normal"

this will be the result echo

How can I do it in my programming language?

as long the output is interpreted by an ANSI compatible terminal you only have to print the escape code, for example, the above command can be used as a string in console.log

console.log("I'm normal \x1b[32m I will be gre
en \x1b[47m I will have white background \x1b[4m
I will be undescored \x1b[0m not I'm back to norm
al")

These are some other cool escape codes you can try

Have fun!

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

Some other cool colored and formatted text

man output of man command

gatsby part of GatsbyJS build script

Sharing is caring

Blog by Jaga Santagostino.
Software consultant, polyglot developer, maker of things, lifelong learner.
ReactJS Milano & milano.dev organizer