Catalog / ANSI Escape Codes Cheatsheet

ANSI Escape Codes Cheatsheet

A quick reference guide to ANSI escape codes, essential for adding color and formatting to terminal output. This cheat sheet covers text styles, colors, cursor movement, and useful bash utilities, making it easy to customize your command-line interface.

Text Formatting

Basic Formatting Codes

\033[0m

Clear all formatting (reset to default).

\033[1m

Bold or increased intensity.

\033[4m

Underline.

\033[5m

Blink (may not work in all terminals).

\033[7m

Invert (swap foreground and background colors).

\033[8m

Hidden (useful for passwords).

Foreground Colors (30-37)

\033[30m

Black foreground.

\033[31m

Red foreground.

\033[32m

Green foreground.

\033[33m

Yellow foreground.

\033[34m

Blue foreground.

\033[35m

Magenta foreground.

\033[36m

Cyan foreground.

\033[37m

White foreground.

Background Colors & Extended Colors

Background Colors (40-47)

\033[40m

Black background.

\033[41m

Red background.

\033[42m

Green background.

\033[43m

Yellow background.

\033[44m

Blue background.

\033[45m

Magenta background.

\033[46m

Cyan background.

\033[47m

White background.

Extended Color Codes (256 Colors)

Use the following format to access 256 colors:
\033[38;5;<color_code>m for foreground
\033[48;5;<color_code>m for background

Where <color_code> is a number between 0 and 255.

Example:
\033[38;5;46m - Sets the foreground color to color code 46.

Cursor Movement & Screen Control

Cursor Movement Codes

\033[<L>A

Move the cursor up L lines.

\033[<L>B

Move the cursor down L lines.

\033[<C>C

Move the cursor forward C columns.

\033[<C>D

Move the cursor backward C columns.

\033[<R>;<C>H or \033[<R>;<C>f

Move the cursor to row R, column C.

\033[s

Save the current cursor position.

\033[u

Restore the last saved cursor position.

Screen Control Codes

\033[2J

Clear the entire screen.

\033[K

Clear the line from the cursor to the end of the line.

\033[1K

Clear the line from the cursor to the beginning of the line.

\033[2K

Clear the entire line.

\033[0;0H

Move cursor to top left corner (0,0).

Bash Utilities & Examples

Bash Functions

hide_cursor() { printf "\e[?25l"; }
show_cursor() { printf "\e[?25h"; }

Usage:

Call hide_cursor to hide the cursor and show_cursor to make it visible again.

Examples

# Make text bold and red
echo "\033[1;31mThis is bold red text\033[0m"

# Set background to blue and foreground to white
echo "\033[44;37mWhite text on blue background\033[0m"

# Underline and set foreground to green
echo "\033[4;32mUnderlined green text\033[0m"
# Clear screen and move cursor to top left
echo "\033[2J\033[0;0H"