How do I output coloured text to a Linux terminal?
How do I print coloured characters to a Linux terminal that supports it? How do I tell whether the terminal supports colour codes?
To determine what the terminal is capable of, check the terminal capabilities database. see termcap(5) .
Feel free to have a look at a code snippet I put here. It’s a small tool that colors its output with the help of some macros.
«The termcap database is an obsolete facility for describing the capabilities of character-cell terminals and printers. It is retained only for capability with old programs; new ones should use the terminfo(5) database and associated libraries.» — termcap(5)
If you want to do some advanced stuff with color printing, I suggest you read this article. I found it very helpful
16 Answers 16
You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Here, \033 is the ESC character, ASCII 27. It is followed by [ , then zero or more numbers separated by ; , and finally the letter m . The numbers describe the colour and format to switch to from that point onwards.
The codes for foreground and background colours are:
foreground background black 30 40 red 31 41 green 32 42 yellow 33 43 blue 34 44 magenta 35 45 cyan 36 46 white 37 47
Additionally, you can use these:
reset 0 (everything back to normal) bold/bright 1 (often a brighter shade of the same colour) underline 4 inverse 7 (swap foreground and background colours) bold/bright off 21 underline off 24 inverse off 27
See the table on Wikipedia for other, less widely supported codes.
To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100 , gnome-terminal , xterm , screen , . ). Then look that up in the terminfo database; check the colors capability.
@nipponese \033[ and m mark the beginning and end of the escape sequence for ANSI color codes. Ref: en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
I use it defining «manipulators», such as const std::string red(«\033[0;31m»); or const std::string reset(«\033[0m»); . Then, I can write simply cout
I’d look at this for a visualization of the colors: misc.flogisoft.com/bash/tip_colors_and_formatting
Basics
I have written a C++ class which can be used to set the foreground and background color of output. This sample program serves as an example of printing This ->word
#include "colormod.h" // namespace Color #include using namespace std; int main() < Color::Modifier red(Color::FG_RED); Color::Modifier def(Color::FG_DEFAULT); cout "
Source
#include namespace Color < enum Code < FG_RED = 31, FG_GREEN = 32, FG_BLUE = 34, FG_DEFAULT = 39, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49 >; class Modifier < Code code; public: Modifier(Code pCode) : code(pCode) <>friend std::ostream& operator <<(std::ostream& os, const Modifier& mod) < return os << "\033[" << mod.code << "m"; >>; >
Advanced
You may want to add additional features to the class. It is, for example, possible to add the color magenta and even styles like boldface. To do this, just an another entry to the Code enumeration. This is a good reference.
some more: ` FG_DEFAULT = 39, FG_BLACK = 30, FG_RED = 31, FG_GREEN = 32, FG_YELLOW = 33, FG_BLUE = 34, FG_MAGENTA = 35, FG_CYAN = 36, FG_LIGHT_GRAY = 37, FG_DARK_GRAY = 90, FG_LIGHT_RED = 91, FG_LIGHT_GREEN = 92, FG_LIGHT_YELLOW = 93, FG_LIGHT_BLUE = 94, FG_LIGHT_MAGENTA = 95, FG_LIGHT_CYAN = 96, FG_WHITE = 97, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49`
If you define operator
@Nawaz Good idea. Here's an implementation like that: pastebin.com/zWC3t9hC. However I'll keep my original implementation in the answer because I feel that it's more extensible.
Actually I like the first implementation better as you can add a flag to turn colors on or off: Add bool sh; to the class and change the constructor to Modifier (Code pCode, bool show = true) : code(pCode), sh(show) <> . Finally, in the body of the
Before you going to output any color you need make sure you are in a terminal:
[ -t 1 ] && echo 'Yes I am in a terminal' # isatty(3) call in C
Then you need to check terminal capability if it support color
on systems with terminfo (Linux based) you can obtain quantity of supported colors as
Number_Of_colors_Supported=$(tput colors)
on systems with termcap (BSD based) you can obtain quantity of supported colors as
Number_Of_colors_Supported=$(tput Co)
BTW, do not use coloring as it was suggested before with ESC characters. Use standard call to terminal capability that will assign you CORRECT colors that particular terminal support.
fg_black="$(tput AF 0)" fg_red="$(tput AF 1)" fg_green="$(tput AF 2)" fg_yellow="$(tput AF 3)" fg_blue="$(tput AF 4)" fg_magenta="$(tput AF 5)" fg_cyan="$(tput AF 6)" fg_white="$(tput AF 7)" reset="$(tput me)"
fg_black="$(tput setaf 0)" fg_red="$(tput setaf 1)" fg_green="$(tput setaf 2)" fg_yellow="$(tput setaf 3)" fg_blue="$(tput setaf 4)" fg_magenta="$(tput setaf 5)" fg_cyan="$(tput setaf 6)" fg_white="$(tput setaf 7)" reset="$(tput sgr0)"
Isn't this bash specific? -t 1 obviously won't work in C++, and calling this tput program will make it very roundabout when in a C++ program.
@Macha, yes, [ -t 1 ] it's sh/bash specific, but on the right side after #(comment) sign there is C function that do the same. man 3 isatty should help on this 😉 Example shown as shell commands to simplify explanation of main point. As about tput it's OPEN source utility to query standard terminal capability interface.
Im not sure why people keep suggesting to use those codes directly. It is really, really bad practice to make such assumptions. Even if this is shell specific code, it can be translated by anyone with even a novice amount of shell experience.
tput is damn slow working with C++, e.g. in an REPL implementation (each can take 0.06s, while typically a C++ process with dynamic system libraries has a total overhead of 0.02s in the startup and termination). And it is still not that portable: ANSI escape code but not tput would just work fine with some new versions of Windows 10 or ConEmu with hook enabled. Even tput is available, it still needs to care about differences over terminfo v. termcap .
In fact, I just come here to find the improvement of my implementation in C++. Seems nobody has already inline the tput calls in C/C++ by hand.
As others have stated, you can use escape characters. You can use my header in order to make it easier:
#ifndef _COLORS_ #define _COLORS_ /* FOREGROUND */ #define RST "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" #define FRED(x) KRED x RST #define FGRN(x) KGRN x RST #define FYEL(x) KYEL x RST #define FBLU(x) KBLU x RST #define FMAG(x) KMAG x RST #define FCYN(x) KCYN x RST #define FWHT(x) KWHT x RST #define BOLD(x) "\x1B[1m" x RST #define UNDL(x) "\x1B[4m" x RST #endif /* _COLORS_ */
An example using the macros of the header could be:
#include #include "colors.h" using namespace std; int main()
From my understanding, a typical ANSI color code
is composed of (name and codec)
With this information, it is easy to colorize a string "I am a banana!" with forground color "Yellow" and background color "Green" like this
"\033[0;33;42mI am a Banana!\033[0m"
More examples with FORMAT ATTRIBUTE here
Basically the same content like the high rated answer on top but easier to understand and more detailed. Up vote from my side. I really like the "blink". World get ready to see blinking terminals!
I use the following solution, it's quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:
const std::string red("\033[0;31m"); const std::string green("\033[1;32m"); const std::string yellow("\033[1;33m"); const std::string cyan("\033[0;36m"); const std::string magenta("\033[0;35m"); const std::string reset("\033[0m"); std::cout
This is an old topic, but I wrote a class with nested subclasses and static members for colors defined by simple C macros.
I got the color function from this post Color Text In C Programming in dreamincode.net by user no2pencil.
I made it this way so to be able to use the static constants in std::cout stream like this:
The class and a test program source code can be downloaded here.
cc::console will reset to console default colors and attributes, cc::underline will underline the text, which works on putty which I've tested the test program.
black blue red magenta green cyan yellow white lightblack lightblue lightred lightmagenta lightgreen lightcyan lightyellow lightwhite
Which can be used with both fore and back static subclasses of the cc static class.
I'm just adding the class code here to be more practical.
#define CC_CONSOLE_COLOR_DEFAULT "\033[0m" #define CC_FORECOLOR(C) "\033[" #C "m" #define CC_BACKCOLOR(C) "\033[" #C "m" #define CC_ATTR(A) "\033[" #A "m"
and the main color function that defines a color or an attribute to the screen:
char *cc::color(int attr, int fg, int bg) < static char command[13]; /* Command is the control command to the terminal */ sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40); return command; >
#include #define CC_CONSOLE_COLOR_DEFAULT "\033[0m" #define CC_FORECOLOR(C) "\033[" #C "m" #define CC_BACKCOLOR(C) "\033[" #C "m" #define CC_ATTR(A) "\033[" #A "m" namespace zkr < class cc < public: class fore < public: static const char *black; static const char *blue; static const char *red; static const char *magenta; static const char *green; static const char *cyan; static const char *yellow; static const char *white; static const char *console; static const char *lightblack; static const char *lightblue; static const char *lightred; static const char *lightmagenta; static const char *lightgreen; static const char *lightcyan; static const char *lightyellow; static const char *lightwhite; >; class back < public: static const char *black; static const char *blue; static const char *red; static const char *magenta; static const char *green; static const char *cyan; static const char *yellow; static const char *white; static const char *console; static const char *lightblack; static const char *lightblue; static const char *lightred; static const char *lightmagenta; static const char *lightgreen; static const char *lightcyan; static const char *lightyellow; static const char *lightwhite; >; static char *color(int attr, int fg, int bg); static const char *console; static const char *underline; static const char *bold; >; >
#include "ccolor.h" using namespace std; namespace zkr < enum Color < Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default = 9 >; enum Attributes < Reset, Bright, Dim, Underline, Blink, Reverse, Hidden >; char *cc::color(int attr, int fg, int bg) < static char command[13]; /* Command is the control command to the terminal */ sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40); return command; >const char *cc::console = CC_CONSOLE_COLOR_DEFAULT; const char *cc::underline = CC_ATTR(4); const char *cc::bold = CC_ATTR(1); const char *cc::fore::black = CC_FORECOLOR(30); const char *cc::fore::blue = CC_FORECOLOR(34); const char *cc::fore::red = CC_FORECOLOR(31); const char *cc::fore::magenta = CC_FORECOLOR(35); const char *cc::fore::green = CC_FORECOLOR(92); const char *cc::fore::cyan = CC_FORECOLOR(36); const char *cc::fore::yellow = CC_FORECOLOR(33); const char *cc::fore::white = CC_FORECOLOR(37); const char *cc::fore::console = CC_FORECOLOR(39); const char *cc::fore::lightblack = CC_FORECOLOR(90); const char *cc::fore::lightblue = CC_FORECOLOR(94); const char *cc::fore::lightred = CC_FORECOLOR(91); const char *cc::fore::lightmagenta = CC_FORECOLOR(95); const char *cc::fore::lightgreen = CC_FORECOLOR(92); const char *cc::fore::lightcyan = CC_FORECOLOR(96); const char *cc::fore::lightyellow = CC_FORECOLOR(93); const char *cc::fore::lightwhite = CC_FORECOLOR(97); const char *cc::back::black = CC_BACKCOLOR(40); const char *cc::back::blue = CC_BACKCOLOR(44); const char *cc::back::red = CC_BACKCOLOR(41); const char *cc::back::magenta = CC_BACKCOLOR(45); const char *cc::back::green = CC_BACKCOLOR(42); const char *cc::back::cyan = CC_BACKCOLOR(46); const char *cc::back::yellow = CC_BACKCOLOR(43); const char *cc::back::white = CC_BACKCOLOR(47); const char *cc::back::console = CC_BACKCOLOR(49); const char *cc::back::lightblack = CC_BACKCOLOR(100); const char *cc::back::lightblue = CC_BACKCOLOR(104); const char *cc::back::lightred = CC_BACKCOLOR(101); const char *cc::back::lightmagenta = CC_BACKCOLOR(105); const char *cc::back::lightgreen = CC_BACKCOLOR(102); const char *cc::back::lightcyan = CC_BACKCOLOR(106); const char *cc::back::lightyellow = CC_BACKCOLOR(103); const char *cc::back::lightwhite = CC_BACKCOLOR(107); >
Раскраска вывода команд в консоли
При выполнении команд в консоли мы чаще всего получаем в результате одноцветный текст, который бывает затруднительно прочитать. Для того, чтобы облегчить чтение результата в консоли, шрифт можно раскрасить. Это, к тому же, придаст оригинальности вашей системе.
Для того, чтобы раскрашивать вывод команд в консоли (подсвечивать результат), можно воспользоваться утилитой Generic Colouriser (grc). Для установки утилиты (в Ubuntu) выполните в командной строке:
Данная утилита использует файлы конфигурации, в которых прописаны регулярные выражения (Regular Expression), содержащие правила раскрашивания. Вместе с утилитой устанавливаются несколько файлов конфигурации для некоторых Linux команд (располагаются в директории /usr/share/grc). Информацию по составлению своих собственных файлов вы можете прочитать в README файле.
Теперь нам нужно прописать алиасы тем командам, вывод которых мы хотим раскрашивать. Фактически для этих команд мы будем вызывать утилиту grc с указанием того, какую команду нам нужно раскрасить. Алиасы прописываются в файле ~/.bashrc. Откроем файл .bashrc, для этого выполним в консоли команду:
В конец файла добавим следующие строки:
if [ -f /usr/bin/grc ]; then alias cvs="grc --colour=auto cvs" alias diff="grc --colour=auto diff" alias esperanto="grc --colour=auto esperanto" alias gcc="grc --colour=auto gcc" alias irclog="grc --colour=auto irclog" alias ldap="grc --colour=auto ldap" alias log="grc --colour=auto log" alias netstat="grc --colour=auto netstat" alias ping="grc --colour=auto ping" alias proftpd="grc --colour=auto proftpd" alias traceroute="grc --colour=auto traceroute" alias wdiff="grc --colour=auto wdiff" fi
Тем самым мы прописали алиасы для команд, вывод которых будет раскрашиваться. Теперь выйдите и войдите в систему, чтобы применить данные настройки. Выполните для примера команду ping и вы должны получить красивый результат: