Linux terminal change color

BASH Shell Change The Color of Shell Prompt on Linux or UNIX

H ow do I change the color of my shell prompt under Linux or Unix operating systems? How do I customize and colorize my Bash prompt (PS1) on a Linux, macOS or Unix-like system?

You can change the color of your shell prompt to impress your friend or to make your own life quite easy while working at the command prompt. BASH shell is the default under Linux and Apple OS X. Your current prompt setting is stored in a shell variable called PS1. There are other variables too, like PS2, PS3 and PS4. Let us see how to change the color of shell prompt on a Linux or Unix system when using bash.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash
Est. reading time 5m

Bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters.

Task: Displaying current BASH prompt (PS1)

Use the echo command/printf command to display current BASH prompt settings:
$ echo «$PS1»
## OR ##
$ printf «%s\n» «$PS1»
Here is what I see:

Here is another output from my Debian based system:
$ echo $PS1
Ubuntu/Debian based Linux distro displayed the following:

By default the command prompt is set to [\u@\h \W]\$ . The backslash-escaped special characters are decoded as follows:

  • \u : Display the current username .
  • \h : Display the hostname
  • \W : Print the base of current working directory.
  • \$ : Display # (indicates root user) if the effective UID is 0, otherwise display a $.

Task: Modifing current BASH prompt

Before you modify settings save your old prompt using the following command:
oldps1=»$PS1″
So if you messed up, you can switch back easily using the following syntax:
PS1=»$oldps1″
Use the export command to setup a new shell prompt:
$ export PS1=»[\\u@\\H \\W \\@]\\$ »

Fig.01: New prompt in action

  • \H : Display FQDN (fully qualified domain name) hostname.
  • \@ : Display current time in 12-hour am/pm format.

Task: Adding colors to the prompt

To add colors to the shell prompt use the following export command syntax:
‘\e[x;ym $PS1 \e[m’
Where,

  • \e[ : Start color scheme.
  • x;y : Color pair to use (x;y)
  • $PS1 : Your shell prompt variable.
  • \e[m : Stop color scheme.

Change the color of shell prompt by setting the PS1

To set a red color prompt, type the following export command:
$ export PS1=»\e[0;31m[\u@\h \W]\$ \e[m »

Fig.02: Adding the colors to the prompt

A list of color codes

Color Code
Black 0;30
Blue 0;34
Green 0;32
Cyan 0;36
Red 0;31
Purple 0;35
Brown 0;33
Blue 0;34
Green 0;32
Cyan 0;36
Red 0;31
Purple 0;35
Brown 0;33

Note: You need to replace digit 0 with 1 to get light color version.

Источник

How To Change Terminal Color in Ubuntu Linux: Background and Text

Ubuntu Linux terminal color generally, by default is magenta or black. And if you are not comfortable with the default color you change both background and font or text color of the Ubuntu Linux shell. People generally prefer the Ubuntu terminal’s default color which is black background and white text color to avoid any kind of distraction. But you can be creative for fun in front of your friends by changing the bash background color in Ubuntu.

Tutorial to customize or change the Ubuntu terminal text and background colors

Note: For performing this, Ubuntu default color change guide, we are using the Ubuntu 17.04.

Step 1: Run the Ubuntu command terminal.

Step 2: Hover on the top bar of the Ubuntu and the menu will appear. Select the option “Profile Preference

Step 3: Under the Profile preference you can set multiple things like Ubuntu terminal font size, Command preference, Text and background colors, and compatibility.

Here in this tutorial, we will select the color tab and under that, you will find all color customization settings.

First of all, uncheck the option “Use colors from system theme” that meant to instruct the Ubuntu terminal to use the default colors.

Now go to “Built-in schemes“, from where either you can choose the pre-defined color combination of text and background such as Black on light yellow, Black on white, Gray on black, Green on black, White on black, Solarized light, Solarized dar or custom. The Custom option allows to choose the color of your choice for background and Text in Ubuntu terminal.

Step 4: After selecting the Custom color scheme, now, at the front of Default color option you will see two colors one is for Text and other is the background.

To change the Ubuntu terminal background color, click on the color box given just below it. As soon as you click on it the “Choose Terminal background Color” window will open. From where you can select the predefined colors for Ubuntu terminal background.

To get a more custom colors, click on the ‘+’ icon given just below the custom text as shown in the below screenshot.

Step 5: When you choose the custom color, a color palette will open, from where choose the custom color via sliding the bar or using the color hexadecimal codes.

Step 6: In the same way, you can change the Ubuntu terminal text color.

In the below screenshot, you can see that we have customized the terminal background with green and the text with black.

Note: If you have any confusion or doubts let us know and we will try to solve them.

Источник

Цвета терминала Linux

Одно из главных преимуществ Linux заключается в том, что при желании в нём можно настроить всё, что угодно. В этом и выражается преимущество проективных систем, над процедурными. Фактически, это конструктор, состоящий из отдельных блоков, каждый из которых можно настроить по своему желанию.

Особенно интересно, если не просто копируешь чужой «рецепт», а пытаешься разобраться, что и как устроено. И даже решая несерьезную задачу, узнаешь что-то новое.

Раскрашиваем цвета вывода ls

Как-то захотелось мне настроить цвета терминала linux в выводе команды ls. Ну не нравился блекло-фиолетовый цвет для каталогов в Linux Mint. Начал разбираться.

Из документации к ls, выяснил, что установка цветов для вывода осуществляется при помощи утилиты dircolors, которая либо устанавливает параметры цвета из своей собственной базы, либо берет их из файла

/.dircolors. Такого файла в моем домашнем каталоге не было. Также упоминалось, что инициализация использования цветов происходит через

/.bashrc, файл с настройками командной оболочки, а сами параметры определяются через переменную LC_COLORS.

Действительно, в .bashrc обнаружился скрипт следующего содержания:

Его суть сводится к проверке на наличие утилиты dircolors в системе, присваивания значения переменной и, при удачном выполнении, использовании параметра —color=auto при каждом вызове ls.

Если запустить утилиту dircolors, она выводит значение переменной LC_COLOR.

Также возможен вывод значения переменной LC_COLORS в структурированном виде, указанием ключа:

Поскольку вывод получается длинный, приводить его не буду.

Если перенаправить вывод dircolors -p >

/.dircolors, то будет создан структурированный файл, из которого и будут браться настройки цветов. Редактируя данный файл и устанавливаются настройки цвета для вывода ls.

В созданном файле .dircolors есть подсказка:

Устанавливая последовательность через точку с запятой и получаем нужный нам цвет в консоли linux, согласно перечисленным. Цвета терминала linux от 30 до 37 для цвета шрифта, а с 40 до 47 для фона. К примеру:

DIR 01;34 подразумевает, что имена директорий будут выделяться жирным шрифтом и синим цветом.

Но таким способом получается всего восемь цветов, а современные эмуляторы терминала способны выводить как минимум 256! Выяснилось, что существуют и другие способы установки цвета. К примеру, значение EXEC 38;5;208;1 — даёт оранжевый толстый шрифт у исполняемых файлов.

Чтобы не перебирать цвета linux вручную, есть уже готовая таблица цветов:

Подставляя в значение цвета 38;5;x — где x цвет из таблицы, получаем необходимый результат. Получается что-то вроде этого:

Но как это работает? Дело в том, что установка цвета вывода информации в эмуляторе терминала осуществляется при помощи ANSI escape-кодов. Это определенная последовательность символов, которая не выводится на экран, однако влияет на вывод. Называется она так, поскольку начинается с \033[ — кода «Esc». Поскольку терминалов и эмуляторов терминалов существует множество, эти управляющие коды стандартизированы. Управлением цветом через последовательность от 30 до 37 — это стандарт ECMA-48. Информация о нем содержится в разделе console_codes. А управление через 38;5;* — определено стандартом T.416. Более подробная информация есть, конечно же, в Википедии.

Раскрашиваем и изменяем строку приглашения:

Разобравшись, как устанавливать цвета linux через esc-коды, не составит труда переделать и раскрасить строку приглашения. За ее вывод отвечает переменная PS1, которая определена в файле

В Linux Mint скрипт ее инициализации имеет следующий вид:

То-есть сперва определяется, запустил ли скрипт root или обычный пользователь. Поскольку в подавляющем большинстве случаев имеет место именно второй вариант, то и редактировать нужно строку, следующую после первого ‘else’. Формат строки расшифрован в документации по баш, в разделе «Promting». Из него следует, что esc-последовательность должна начинаться с «\[» и заканчиваться «\]». Таким образом:

  • [\033[01;32m\] — устанавливает зеленый цвет;
  • \u — выводит имя пользователя;
  • \h — выводит имя хоста;
  • [\033[00m\] — очищает установленные атрибуты;
  • [\033[01;34m\] — устанавливает синий цвет;
  • \w — выводит имя рабочей директории;
  • Привет! — пример того, что может быть выведен любой производный текст.

Что ещё можно вывести в строке приглашения:

  • \d — дату, в формате «Wed Dec 28»;
  • \A — время в 24-часовом формате;
  • \! — номер текущей команды в истории;
  • \n — перенос вывода на другую строку;

Введем что нибудь поинтереснее:

И строка приглашения примет вид:

Так, не понял, а откуда взялась ёлка-то?

Ну ладно, на самом деле, если в конец .bashrc вставить echo -e «С Новым годом», то поздравление будет выводиться при каждом запуске терминала перед приглашением ввода. Соответственно, вывод можно раскрашивать каким угодно способом. А там уж и ёлку нарисовать не сложно.

Источник

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 value of 38 or 48 (respectively) in the following command:

For example, to set the foreground color ( = 38 ) to red ( = 196 ) and the background color ( = 48 ) to black ( = 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 value of 38 or 48 (respectively) in the following command:

For example, to set the foreground color ( = 38 ) to red ( = 255 , = 0 , = 0 ) and the background color ( = 48 ) to black ( = 0 , = 0 , = 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:

Источник

Читайте также:  Тест ком порта линукс
Оцените статью