How to do: underline, bold, italic, strikethrough, color, background, and size in Gnome Terminal?

The ANSI/VT100 terminals and terminal emulators are not just able to display black and white text; they can display colors and formatted texts thanks to escape sequences. Those sequences are composed of the Escape character (often represented by "^[" or "Esc") followed by some other characters: "Esc[FormatCodem".

In Bash, the character can be obtained with the following syntaxes:

\e
\033
\x1B

enter image description here

The commands (for easy copy-paste):

echo -e "\e[1mbold\e[0m"
echo -e "\e[3mitalic\e[0m"
echo -e "\e[3m\e[1mbold italic\e[0m"
echo -e "\e[4munderline\e[0m"
echo -e "\e[9mstrikethrough\e[0m"
echo -e "\e[31mHello World\e[0m"
echo -e "\x1B[31mHello World\e[0m"

Source (including all types of foreground/background color codes): http://misc.flogisoft.com/bash/tip_colors_and_formatting


To extend Sylvain's answer, some helper functions:

ansi()          { echo -e "\e[${1}m${*:2}\e[0m"; }
bold()          { ansi 1 "$@"; }
italic()        { ansi 3 "$@"; }
underline()     { ansi 4 "$@"; }
strikethrough() { ansi 9 "$@"; }
red()           { ansi 31 "$@"; }

Then

enter image description here


Something that has not been covered yet is the combination of two or three parameters, e. g. bold and underline, in a predefined color. This is achieved by a 3-way syntax, for instance:

~$ printf "\e[3;4;33mthis is a test\n\e[0m"

will cause "this is a test" to be printed in yellow color (33m), italic (3m) AND underlined (4m).
Note that it is not necessary to repeat the \e[ every time.
Note too that (alike to Sylvain) I also added a \e[0m to reset settings every time, because otherwise the yellow color and the font style will remain active in terminal! Needless to say that you absolutely have to watch out for these to get reset in scripts, because users who use your scripts may dislike it if your script permanently modifies their color + style settings in terminal!