11

How do I format text with ANSI escaping?

Like make things italic or bold and maybe strikethrough and super script.

Sebastián Grignoli
  • 32,444
  • 17
  • 71
  • 86
jepjep40
  • 181
  • 1
  • 2
  • 12
  • Possible duplicate of [Enable bash output color with Lua script](http://stackoverflow.com/questions/1718403/enable-bash-output-color-with-lua-script) – Thomas Dickey Jul 27 '16 at 08:34

2 Answers2

22

How I format like, make things italic or bold using ANSI terminal escape codes?

Bold: Use ESC[1m

Italic, Strike-through and Superscript are not supported.

Some terminals support additional sequences. For example in a Gnome Terminal you can use:

echo -e "\e[1mbold\e[0m"
echo -e "\e[3mitalic\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"

enter image description here

Source How to do: underline, bold, italic, strikethrough, color, background, and size in Gnome Terminal?, answer by Sylvain Pineau


Further Reading

DavidPostill
  • 7,734
  • 9
  • 41
  • 60
0

Italic, Strike-through and Superscript are not supported.

Not over here. I wrote the following script and tested it on:

  • iTerm2 on macOS (zsh)
  • Terminal on macOS (zsh)
  • Git Bash on Windows 11
  • GNOME Terminal on Ubuntu, Mint (bash)
  • Konsole on FreeBSD 13 (bash)

And they all worked, but I didn't see any reference to "superscript" though. What's the esc code for that?

Anyway, I put this script online if anyone wants to try it: esctest.sh. (don't forget to chmod +x first)

PS. You can use \x1b, \033 and \e all interchangeably for the ESC.

#!/bin/bash

_esc_seq="\x1b["
_esc_end="${_esc_seq}0m"

# $1: escape code
# $2: message
print_test_style() {
    echo -e "\t${_esc_seq}${1}m${2}${_esc_end}\n"
}

declare -a _style_codes=(
    ["1"]="bold"
    ["2"]="dim"
    ["3"]="emphasis"
    ["4"]="underline"
    ["9"]="strikethrough"
)

echo -e "Testing styles...\n"

for key in "${!_style_codes[@]}"; do
    print_test_style "${key}" "${_style_codes[$key]}"
done

sample of iTerm2 running this script

aremmell
  • 1,151
  • 1
  • 10
  • 15