Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a2650e628432deb • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Changing colour of text and background of terminal?
I can change the colour through preference , but how can I change the background colour and text colour of terminal through the command line?
![]()
![]()
5 Answers 5
On certain XTerm/ANSI-compatible terminals (like xterm and gnome-terminal ), you can set colors using a palette bigger then the default 8/16-colors palette (for example using an 88-colors, 256-colors or 16777216-colors (RGB) palette; both xterm and gnome-terminal support both the 256-colors and the 16777216-colors (RGB) palette); mind that the shell might override this (this is the case e.g. for zsh ).
Here’s a script to list the colors in the 256-color palette along with their ANSI color code in XTerm/ANSI-compatible terminals with a 256-color palette support:


Depending on whether you want to apply the color to the foreground or to the background, use an <fg_bg> value of 38 or 48 (respectively) in the following command:
For example, to set the foreground color ( <fg_bg> = 38 ) to red ( <ANSI_color_code> = 196 ) and the background color ( <fg_bg> = 48 ) to black ( <ANSI_color_code> = 0 ):

It’s necessary to redraw the prompt using printf ‘\e[K’ in order for the background color to apply to the whole line and in order for the foreground color to apply to the cursor:
The same thing can be accomplished using RGB values instead of ANSI color codes in a compatible terminal; depending on whether you want to apply the color to the foreground or to the background, use an <fg_bg> value of 38 or 48 (respectively) in the following command:
For example, to set the foreground color ( <fg_bg> = 38 ) to red ( <R> = 255 , <G> = 0 , <B> = 0 ) and the background color ( <fg_bg> = 48 ) to black ( <R> = 0 , <G> = 0 , <B> = 0 ):

Again, it’s necessary to redraw the prompt using printf ‘\e[K’ in order for the background color to apply to the whole line and in order for the foreground color to apply to the cursor:

Using either methods, you can use printf ‘\e[0m’ to reset all the attributes:
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?
![]()
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:
Additionally, you can use these:
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.
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<- is red. and formatting it so that the foreground color of word is red.
Source
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.
![]()
Before you going to output any color you need make sure you are in a terminal:
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
on systems with termcap (BSD based) you can obtain quantity of supported colors as
Then make you decision:
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.
BSD Based Linux Based Use As
![]()
As others have stated, you can use escape characters. You can use my header in order to make it easier:
An example using the macros of the header could be:

![]()
From my understanding, a typical ANSI color code
is composed of (name and codec)
RESET FORMAT ATTRIBUTE
With this information, it is easy to colorize a string "I am a banana!" with forground color "Yellow" and background color "Green" like this
Or with a C++ library colorize
More examples with FORMAT ATTRIBUTE here
I use the following solution, it’s quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:
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.
Which can be used with both fore and back static subclasses of the cc static class.
EDIT 2017
I’m just adding the class code here to be more practical.
The color code macros:
and the main color function that defines a color or an attribute to the screen:
Как изменить цвет текста в терминале Linux

Обычно вывод текста в терминале пользователя выглядит слишком монохромно. Однако добавить больше красок — совсем несложно. В данном скрипте я предлагаю вспомогательные методы для вывода текста, использования заданных цветов и работы с окнами терминала в тёмном и светлом режимах.
⬇️ Скачать color.zip — 2.7 KB (прим. редактора — потребуется регистрация на сайте)
Введение
Текст, выводимый в терминале по умолчанию, является одноцветным и не предоставляет простого способа указать на контекст. Например, вы можете захотеть, чтобы ошибка отображалась красным цветом, успех — зелёным, или чтобы важная информация была выделена жирным шрифтом.
Добавление цвета к выводу текста в терминале — простая задача, которая заключается в выводе правильных управляющих символов перед вашим текстом.
Цвета в терминале
| Цвет | Основной | Фон |
|---|---|---|
| Стандартный | \033[39m | \033[49m |
| Чёрный | \033[30m | \033[40m |
| Тёмно-красный | \033[31m | \033[41m |
| Тёмно-зелёный | \033[32m | \033[42m |
| Тёмно-жёлтый «Оранжевый» | \033[33m | \033[43m |
| Тёмно-синий | \033[34m | \033[44m |
| Темно-пурпурный | \033[35m | \033[45m |
| Тёмно-голубой | \033[36m | \033[46m |
| Светло-серый | \033[37m | \033[47m |
| Тёмно-серый | \033[90m | \033[100m |
| Красный | \033[91m | \033[101m |
| Зелёный | \033[92m | \033[101m |
| Оранжевый | \033[93m | \033[103m |
| Синий | \033[94m | \033[104m |
| Пурпурный | \033[95m | \033[105m |
| Голубой | \033[96m | \033[106m |
| Белый | \033[97m | \033[107m |
и код сброса \033[0m
Формат строки для основного цвета:
Эти коды могут быть использованы вместе для одновременного изменения основного цвета и фона.
Применяем код
Простой пример красного текста:
Пример красного текста на белом фоне:
Это выглядит довольно громоздко, так что я создал несколько простых подпрограмм, которые позволят задать цвет текста более изящным способом.
Вспомогательные функции
Следующие вспомогательные функции позволяют вам делать такие вещи, как:
Работа с тёмным и светлым режимами
Во многих дистрибутивах Linux и Unix терминал имеет чёрный фон и белый текст. В macOS по умолчанию используется белый фон с чёрным текстом. Конечно, есть способы и средства для смены тёмного/светлого режима, но вам придется проверять и тестировать всё на собственной системе, чтобы найти то, что подходит именно вам.
Я предполагаю, что если мы используем mac, то можем всё протестировать напрямую, в противном случае — мы предполагаем черный фон и белый текст. Я также стараюсь придерживаться цветов по умолчанию, а там, где мне нужно немного цвета, я предпочитаю использование некоторых предопределённых цветов, которые, по моим представлениям, будут хорошо работать везде.
Как только мы получим приблизительное представление о том, с чем имеем дело, я выполню код ниже:
и также воспользуюсь этими строками:
Получаем примерно такую картину в классическом терминале Linux:

И такую в macOS:

Всё немного запутано, поэтому давайте добавим ещё одну функцию, которая обеспечит контрастный передний план на любом выбранном нами фоне:
Затем, в подпрограмме Color, мы можем сделать следующее:
… и чтобы сделать наш текст с изменённым цветом фона немного более разборчивым, мы используем следующие строки: