Linux echo with color

Цветной man или как разукрасить вывод echo

echo -e # ключ -e в комманде echo включает отображение «backslash escapes» ; например \n — переход на следующую строку, \t -табуляция
echo -n # ключ -n в команде echo сигнализирует, что после вывода информации не нужно переходить на следующую строку.
echo -en # в нашем случае поможет раскрасить вывод текста.

2) Хорошая статья с примерами «Управление консолью Linux» RUS
c-reaction.net/content/204

Для начала одним глазом хотябы посмотрим на man echo rus, а потом рассмотрим как использовать цвет
www.opennet.ru/man.shtml?topic=echo&category=1

Переходим к Управлению цветом:

tput sgr0 Возврат цвета в «нормальное» состояние

\033[0m все атрибуты по умолчанию
\033[1m жирный шрифт (интенсивный цвет)
\033[2m полу яркий цвет (тёмно-серый, независимо от цвета)
\033[4m подчеркивание
\033[5m мигающий
\033[7m реверсия (знаки приобретают цвет фона, а фон — цвет знаков)

\033[22m установить нормальную интенсивность
\033[24m отменить подчеркивание
\033[25m отменить мигание
\033[27m отменить реверсию

\033[30 чёрный цвет знаков
\033[31 красный цвет знаков
\033[32 зелёный цвет знаков
\033[33 желтый цвет знаков
\033[34 синий цвет знаков
\033[35 фиолетовый цвет знаков
\033[36 цвет морской волны знаков
\033[37 серый цвет знаков

\033[40 чёрный цвет фона
\033[41 красный цвет фона
\033[42 зелёный цвет фона
\033[43 желтый цвет фона
\033[44 синий цвет фона
\033[45 фиолетовый цвет фона
\033[46 цвет морской волны фона
\033[47 серый цвет фона

black 30 40 \033[30m \033[40m
red 31 41 \033[31m \033[41m
green 32 42 \033[32m \033[42m
yellow 33 43 \033[33m \033[43m
blue 34 44 \033[34m \033[44m
magenta 35 45 \033[35m \033[45m
cyan 36 46 \033[36m \033[46m
grey 37 47 \033[37m \033[47m

Допускается объединение этих управляющих последовательностей.
Например \033[1m\033[5m\033[36m может быть заменено эквивалентной последовательностью \033[1;5;36m.

#!/bin/sh
#
# скрипт выводит на экран сообщение с использованием цвета
#
echo -en «\033[37;1;41m Внимание \033[0m»

#!/bin/sh
#
# скрипт запускает копию командного интерпретатора sh
# с цветным приглашением
#
export PS1= «\[\033[1;30m\][\[\033[0m\]\t\[\033[1;30m\];\
\[\033[0m\]\W\[\033[1;30m\]]\[\033[36;1m\]|\[\033[0m\] »
echo «Now runing a new copy of shell width color prompt»
echo -en «use \033[1;36mexit\033[0m command or»
echo -e «\033[1;36m^D\033[0m to return back»
sh
#
# обратите внимание на то, что управляющие последовательности
# заключены в скобки «\[» и «\]»
# Это сделано для того, чтобы shell не учитывал их при
# оценке длины строки.
# В противном случае длинные строки будут переноситься неверно.
#

Для удобства пользвания можно цвет и доп. свойства назначить переменным:

Файл .sh должен быть в формате UNIX и с кодировкой UTF-8

Ну и напоследок — один хороший пример со всеми плюшками:

#!/bin/sh
# echo подсветка
# echo color
# Скрипт выводит на экран список меню

#Памятка, Таблица цветов и фонов
#Цвет код код фона

#black 30 40 \033[30m \033[40m
#red 31 41 \033[31m \033[41m
#green 32 42 \033[32m \033[42m
#yellow 33 43 \033[33m \033[43m
#blue 34 44 \033[34m \033[44m
#magenta 35 45 \033[35m \033[45m
#cyan 36 46 \033[36m \033[46m
#white 37 47 \033[37m \033[47m

Читайте также:  Sublime text аналоги linux

# Дополнительные свойства для текта:
BOLD= ‘\033[1m’ # $ # жирный шрифт (интенсивный цвет)
DBOLD= ‘\033[2m’ # $ # полу яркий цвет (тёмно-серый, независимо от цвета)
NBOLD= ‘\033[22m’ # $ # установить нормальную интенсивность
UNDERLINE= ‘\033[4m’ # $ # подчеркивание
NUNDERLINE= ‘\033[4m’ # $ # отменить подчеркивание
BLINK= ‘\033[5m’ # $ # мигающий
NBLINK= ‘\033[5m’ # $ # отменить мигание
INVERSE= ‘\033[7m’ # $ # реверсия (знаки приобретают цвет фона, а фон — цвет знаков)
NINVERSE= ‘\033[7m’ # $ # отменить реверсию
BREAK= ‘\033[m’ # $ # все атрибуты по умолчанию
NORMAL= ‘\033[0m’ # $ # все атрибуты по умолчанию

# Цвет текста:
BLACK= ‘\033[0;30m’ # $ # чёрный цвет знаков
RED= ‘\033[0;31m’ # $ # красный цвет знаков
GREEN= ‘\033[0;32m’ # $ # зелёный цвет знаков
YELLOW= ‘\033[0;33m’ # $ # желтый цвет знаков
BLUE= ‘\033[0;34m’ # $ # синий цвет знаков
MAGENTA= ‘\033[0;35m’ # $ # фиолетовый цвет знаков
CYAN= ‘\033[0;36m’ # $ # цвет морской волны знаков
GRAY= ‘\033[0;37m’ # $ # серый цвет знаков

# Цветом текста (жирным) (bold) :
DEF= ‘\033[0;39m’ # $
DGRAY= ‘\033[1;30m’ # $
LRED= ‘\033[1;31m’ # $
LGREEN= ‘\033[1;32m’ # $
LYELLOW= ‘\033[1;33m’ # $
LBLUE= ‘\033[1;34m’ # $
LMAGENTA= ‘\033[1;35m’ # $
LCYAN= ‘\033[1;36m’ # $
WHITE= ‘\033[1;37m’ # $

# Цвет фона
BGBLACK= ‘\033[40m’ # $
BGRED= ‘\033[41m’ # $
BGGREEN= ‘\033[42m’ # $
BGBROWN= ‘\033[43m’ # $
BGBLUE= ‘\033[44m’ # $
BGMAGENTA= ‘\033[45m’ # $
BGCYAN= ‘\033[46m’ # $
BGGRAY= ‘\033[47m’ # $
BGDEF= ‘\033[49m’ # $

tput sgr0 # Возврат цвета в «нормальное» состояние

#Начало меню
echo «»
echo -n » »
echo -e «$$$ Меню DNS323 $»
echo «»
echo -en «$ 1 $ Комманды для удобной работы в telnet $(Выполнить?)$\n»
echo «»
echo -en «$ 2 $ Пути к папкам & Изменение прав доступа $(Комманды)$\n»
echo «»
echo -en «$ 3 $ Transmission ($Start$, $Stop$, $Upgrade$) $(Меню)$\n»
echo «»
echo -en «$ 4 $ Копирование (cp & rsync) $(Комманды)$\n»
echo «»
echo -en «$ 5 $ Создание ссылки на файл или папку $(Комманды)$\n»
echo «»
echo -en «$ 6 $ Установка из fun-plug & IPKG $(Комманды)$\n»
echo «»
echo -en «$ 7 $ Показать Трафик ($ n$load) $(Выполнить?)$\n»
echo «»
echo -en «$ 8 $ Диспетчер задач ($ h$top) $(Выполнить?)$\n»
echo «»
echo -en «$ 9 $ Midnight Commander ($ m$c) $(Выполнить?)$\n»
echo «»
echo -en «$ q $ Выход $\n»
echo «»
echo «(Введите пожалуйта номер пункта, чтобы выполнить комманды этого пункта, любой другой ввод, Выход)»
echo «»
tput sgr0

ps: Подскажите, пожалуйста, в какой блог лучше опубликовать?

image

UPD1: перенес в Linux для всех, т.к. это наиболее близкий блог по тематике, как мне кажется.
UPD2: Спасибо aco за картинку, кратко и наглядно =)

Источник

Changing the Color of the echo Command’s Output

Using colors with the echo command could make your shell scripts more user friendly and attractive.

In UNIX-like operating systems, the echo command is used to display a string of characters onto the terminal.

Usually, the color of output of the echo command follows the terminal theme, nothing unusual about that.

But if you want, you can change the color of the output text of the echo command in Linux.

Why would you want to do that? There could be several reasons for that. For examples, if you are writing a script that has a step where it needs to warn the user, using red colored output could be useful.

Using colored output in echo command

Let me tell you how you can change the text color from either black or white to something else entirely, like yellow, red, green.

ANSI escape codes for the colored output

To change the output color of echo command, you have to use escape sequences.

A popular example of an escape sequence that you might have used in the past is what we use for a newline, ‘\n’. Similarly, there are escape sequences for specifying colorized output as well.

Читайте также:  Отключить ipv6 arch linux

Below are a few ANSI escape codes for each color:

Black 0;30 Dark Gray 1;30 Red 0;31 Light Red 1;31 Green 0;32 Light Green 1;32 Brown/Orange 0;33 Yellow 1;33 Blue 0;34 Light Blue 1;34 Purple 0;35 Light Purple 1;35 Cyan 0;36 Light Cyan 1;36 Light Gray 0;37 White 1;37

You can use these escape codes with ‘\033[‘ , followed by the ANSI escape code of the color of your choice, and finally a ‘m’ .

Below are a few examples how to string the ANSI color code together:

R='\033[0;31m' #'0;31' is Red's ANSI color code G='\033[0;32m' #'0;32' is Green's ANSI color code Y='\033[1;32m' #'1;32' is Yellow's ANSI color code B='\033[0;34m' #'0;34' is Blue's ANSI color code

The usage of this escape character is similar to how you use the backslash ‘\’ with ‘n’ to signify a newline.

Colorized output in echo command

You can use the specified colors as a “variable” in the echo command and mention it before any text to make the text appear with said color in the terminal output.

Whenever you use any special escape sequence like ‘\n’, ‘\t’, or these escape sequences for colors with echo command, please make sure to use the «-e» flag with the echo command.

In this example, I have declared two variables with color codes. The first one is for Red and the ‘NOCOLOR’ is to stop red and switch back to the default color.

As you can see, it displayed the text ‘love’ in red. I used it directly in the shell. You can put it in script in the same manner:

#!/bin/bash RED='\033[0;31m' NOCOLOR='\033[0m' echo -e "I $love$ Linux"

Here is another example with more colors in the echo command output:

This time, since the last character in the string of text needs to be in yellow, it is okay to not switch back to the regular color by the use of ‘NOCOLOR’.

You can add color to the output of printf as well

If you want a formatted string, you are better off using the printf command instead of the echo command.

Once you have defined the color’s escape sequences — which are exactly the same as you used for echo, you can use it with printf as well.

Here, I have done the same thing I did for echo, I specified and used the ‘NOCOLOR’ variable to stop using the red color and switch back to default color after the word ‘love’.

Bonus Tip: Use an online tool to generate colors

GitHub user Gbox4 created an extremely helpful website called ‘ANSI code generator’ that helps you generate these escape sequences for you.

It lets you select from a variety of colors for the text background and for the text foreground (text color), styles — bold, italic, underline or strikethrough.

Then you can easily store that automatically generated code into a bash variable for future use.

ANSI escape code generator

Conclusion

Now that you know how to add colors to echo command output, you can make your bash scripts more useful and attractive.

Читайте также:  Arm linux gnueabihf bin ld

Since the printf command is more predictable, allows formatting our output and highly configurable, if you have a specific agenda, I would recommend going the printf route.

If you are achieving a simple task, use the echo command.

Источник

How to Change the Output Color of ‘Echo’ in Linux

The echo command in Linux is used to display a string or a set of strings onto the terminal. The string(s) is passed as an argument to the command. The echo command also comes with a set of options to manipulate how the output is displayed.

Terminals usually have default themes with light-colored text on a dark background or dark-colored text on a light background. Users can even customize it more based on preference. The echo command also displays text based on the color of the text defined in the theme.

In this article, we will see how to modify the output color of the echo command in Linux. For demonstrations, I will be using Ubuntu 20.10, however, this should work well on any other Linux distribution as well.

Modifying Output Color of Echo Command

There are escape sequences (some defined set of characters) that can be used on a Linux terminal to modify the color of the output.

The string to be colored should be preceded with the escape sequence:

Eg. If you want to output it red, it should be:

Here, ‘\e’ signifies the start of the escape sequence, ‘[1’ makes the text bold, 31 is the color code for red, and ‘m’ signifies the end of the escape sequence.

$ echo -e "\e[1;31mHello World!"

Print Colored Output Text

Notice that I passed the flag ‘-e’ as well. This flag will enable the echo command to consider the escape sequences in the string. Without the flag, an echo will print the characters \e[1;31m verbatim.

You can also use multiple colors for different substrings.

$ echo -e "\e[1;31mHello \e[1;35mWorld!"

Print Multi Colored Output Text

The colors in the range 30-39 are for the foreground, i.e. the text. If you want to change the background color, you can do so by using the colors of codes 40 and above.

$ echo -e "\e[1;41mHello World!"

Print Background Colored Output Text

You can see that the background color Red has not only been applied on the text, but also on the console prompt string. To prevent this, end your echo string with an escape string with no color code.

$ echo -e "\e[1;41mHello World!\e[1;m"

No Color Terminal Prompt

You can use many more colors for your string. The list of colors is as follows:

Linux Terminal Color Codes

In this article, we learned how to change the color of output when using the echo command in Linux. Note that while there is a standard built-in implementation of echo in Linux, every interpreter has its own echo command as well, which overrides the default implementation.

You can check the man page of your interpreter to learn if there are any differences to the echo command while printing text in color.

If you have any questions or feedback, feel free to leave a comment below!

Источник

Оцените статью
Adblock
detector