- Делаем Linux терминал красивым и удобным
- Добавляем функциональность
- Командная оболочка
- Настройка Zsh
- Настраиваем внешний вид
- Цвета терминала Linux
- Раскрашиваем цвета вывода ls
- Раскрашиваем и изменяем строку приглашения:
- How To Change Terminal Color in Ubuntu Linux: Background and Text
- Tutorial to customize or change the Ubuntu terminal text and background colors
- How to change the color of your Linux terminal | Opensource.com
- Make Linux as colorful (or as monochromatic) as you want.
- Subscribe now
- What’s your preferred terminal color palette?
- Terminal capabilities
- ANSI color codes
- Foreground and background
- Permanency
- Color
Делаем Linux терминал красивым и удобным
Добавляем функциональность
Командная оболочка
Большинство дистрибутивов поставляется со встроенным Bash. Используя дополнения можно сделать из него все что захотите, но гораздо проще этого добиться с Zsh. Почему?
Настройка Zsh
Для начала, установим Zsh (если он уже установлен, например, как в Manjaro, можете пропустить этот пункт):
Когда вам предложат установить Zsh как оболочка по-умолчанию, нажмите Y , чтоб подтвердить.
Oh-My-Zsh — популярный и активно развивающийся фреймворк Zsh, который позволяет гибко настроить оболочку терминала. Установим его:
Подсветка синтаксиса. Гораздо проще ориентироваться по содержимому терминала, когда разные части команд подсвечены разными цветами. Например, директории будут подчеркиваться, а команды — выделяться цветом, отличным от обычного текста. Установим плагин zsh-syntax-highlighting :
Чтоб плагин заработал, его надо подключить.
/.zshrc меняем строку с plugins= :
Если такой строки нет — добавьте её.
Готово! Получаем удобный и функциональный терминал. Теперь сделаем его визуально приятным.
Настраиваем внешний вид
Скачиваем и добавляем в систему шрифт JetBrains Mono Nerd (c иконками):
Выберитеодин из списка, в папке шрифт/complete выберите шрифт без «Windows Compatible», с окончанием «Mono».
Подключаем шрифт и тему.
Если в файле эти строки уже есть — замените их.
Цвета. Важная часть оформления терминала — цветовая схема. Я перебрал много разных схем, редактировал их, остановился на Monokai Dark. Не режет глаза, но при этом приятная и яркая. Список цветов:
В разных терминалах по-разному меняется цветовая схема (обычно, это делается через настройки терминала), но порядок цветов везде одинаковый. Вы можете импортировать этот шаблон в формате Termite и экспортировать его для вашего терминала через terminal.sexy
Запускаем конфигурацию темы: p10k configure .
Настройте тему, выбирая варианты отображения, которые вам больше нравятся.
Финальный штрих — меняем конфиг темы и заменяем встроенные цвета.
Если в файле эти строки уже есть — замените их. Коды цветов можно получить командой
- Отображение только текущей директории:
Источник
Цвета терминала 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 «С Новым годом», то поздравление будет выводиться при каждом запуске терминала перед приглашением ввода. Соответственно, вывод можно раскрашивать каким угодно способом. А там уж и ёлку нарисовать не сложно.
Источник
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.
Источник
How to change the color of your Linux terminal | Opensource.com
Make Linux as colorful (or as monochromatic) as you want.
Subscribe now
Get the highlights in your inbox every week.
What’s your preferred terminal color palette?
You can add color to your Linux terminal using special ANSI encoding settings, either dynamically in a terminal command or in configuration files, or you can use ready-made themes in your terminal emulator. Either way, the nostalgic green or amber text on a black screen is wholly optional. This article demonstrates how you can make Linux as colorful (or as monochromatic) as you want.
Terminal capabilities
Modern systems usually default to at least xterm-256color, but if you try to add color to your terminal without success, you should check your TERM setting.
Historically, Unix terminals were literally that: physical points at the literal endpoint (termination) of a shared computer system where users could type in commands. They were unique from the teletype machines (which is why we still have /dev/tty devices in Linux today) that were often used to issue commands remotely. Terminals had CRT monitors built-in, so users could sit at a terminal in their office to interact directly with the mainframe. CRT monitors were expensive—both to manufacture and to control; it was easier to have a computer spit out crude ASCII text than to worry about anti-aliasing and other niceties that modern computerists take for granted. However, developments in technology happened fast even then, and it quickly became apparent that as new video display terminals were designed, they needed new capabilities to be available on an optional basis.
For instance, the fancy new VT100 released in 1978 supported ANSI color, so if a user identified the terminal type as vt100, then a computer could deliver color output, while a basic serial device might not have such an option. The same principle applies today, and it’s set by the TERM environment variable. You can check your TERM definition with echo:
/.bashrc configuration file:
Save the file, and reload your settings:
ANSI color codes
Modern terminals have inherited ANSI escape sequences for «meta» features. These are special sequences of characters that a terminal interprets as actions instead of characters. For instance, this sequence clears the screen up to the next prompt:
It doesn’t clear your history; it just clears up the screen in your terminal emulator, so it’s a safe and demonstrative ANSI escape sequence.
ANSI also has sequences to set the color of your terminal. For example, typing this code changes the subsequent text to green:
As long as you see color the same way your computer does, you could use color to help you remember what system you’re logged into. For example, if you regularly SSH into your server, you can set your server prompt to green to help you differentiate it at a glance from your local prompt. For a green prompt, use the ANSI code for green before your prompt character and end it with the code representing your normal default color:
Foreground and background
You’re not limited to setting the color of your text. With ANSI codes, you can control the background color of your text as well as do some rudimentary styling.
For instance, with \033[4m, you can cause text to be underlined, or with \033[5m you can set it to blink. That might seem silly at first—because you’re probably not going to set your terminal to underline all text and blink all day—but it can be useful for select functions. For instance, you might set an urgent error produced by a shell script to blink (as an alert for your user), or you might underline a URL.
For your reference, here are the foreground and background color codes. Foreground colors are in the 30 range, while background colors are in the 40 range:
Color | Foreground | Background |
---|---|---|
Black | \033[30m | \033[40m |
Red | \033[31m | \033[41m |
Green | \033[32m | \033[42m |
Orange | \033[33m | \033[43m |
Blue | \033[34m | \033[44m |
Magenta | \033[35m | \033[45m |
Cyan | \033[36m | \033[46m |
Light gray | \033[37m | \033[47m |
Fallback to distro’s default | \033[39m | \033[49m |
There are some additional colors available for the background:
Color | Background |
---|---|
Dark gray | \033[100m |
Light red | \033[101m |
Light green | \033[102m |
Yellow | \033[103m |
Light blue | \033[104m |
Light purple | \033[105m |
Teal | \033[106m |
White | \033[107m |
Permanency
Setting colors in your terminal session is only temporary and relatively unconditional. Sometimes the effect lasts for a few lines; that’s because this method of setting colors relies on a printf statement to set a mode that lasts only until something else overrides it.
The way a terminal emulator typically gets instructions on what colors to use is from the settings of the LS_COLORS environment variable, which is in turn populated by the settings of dircolors. You can view your current settings with an echo statement:
Or you can use dircolors directly:
If that looks cryptic, it’s because it is. The first digit after a file type is the attribute code, and it has six options:
- 00 none
- 01 bold
- 04 underscore
- 05 blink
- 07 reverse
- 08 concealed
The next digit is the color code in a simplified form. You can get the color code by taking the final digit of the ANSII code (32 for green foreground, 42 for green background; 31 or 41 for red, and so on).
Your distribution probably sets LS_COLORS globally, so all users on your system inherit the same colors. If you want a customized set of colors, you can use dircolors for that. First, generate a local copy of your color settings:
Edit your local list as desired. When you’re happy with your choices, save the file. Your color settings are just a database and can’t be used directly by ls, but you can use dircolors to get shellcode you can use to set LS_COLORS:
Copy and paste that output into your
/.bashrc file and reload. Alternatively, you can dump that output straight into your .bashrc file and reload.
You can also make Bash resolve .dircolors upon launch instead of doing the conversion manually. Realistically, you’re probably not going to change colors often, so this may be overly aggressive, but it’s an option if you plan on changing your color scheme a lot. In your .bashrc file, add this rule:
Should you have a .dircolors file in your home directory, Bash evaluates it upon launch and sets LS_COLORS accordingly.
Color
Colors in your terminal are an easy way to give yourself a quick visual reference for specific information. However, you might not want to lean on them too heavily. After all, colors aren’t universal, so if someone else uses your system, they may not see the colors the same way you do. Furthermore, if you use a variety of tools to interact with computers, you might also find that some terminals or remote connections don’t provide the colors you expect (or colors at all).
Those warnings aside, colors can be useful and fun in some workflows, so create a .dircolor database and customize it to your heart’s content.
Источник