Terminal Escape Sequences
ANSI Escape Codes
Color codes
# Format: \e[<code>m or \033[<code>m
# Reset: \e[0m
# Basic colors (30-37 foreground, 40-47 background)
echo -e "\e[31mRed text\e[0m"
echo -e "\e[32mGreen text\e[0m"
echo -e "\e[33mYellow text\e[0m"
echo -e "\e[34mBlue text\e[0m"
echo -e "\e[41mRed background\e[0m"
# Bright colors (90-97 foreground, 100-107 background)
echo -e "\e[91mBright red\e[0m"
# 256-color mode
echo -e "\e[38;5;208mOrange (color 208)\e[0m" # foreground
echo -e "\e[48;5;57mPurple bg (color 57)\e[0m" # background
# True color (24-bit RGB)
echo -e "\e[38;2;137;180;250mCatppuccin blue\e[0m" # rgb(137,180,250)
echo -e "\e[48;2;30;30;46mCatppuccin base bg\e[0m" # rgb(30,30,46)
Text attributes
echo -e "\e[1mBold\e[0m"
echo -e "\e[2mDim\e[0m"
echo -e "\e[3mItalic\e[0m"
echo -e "\e[4mUnderline\e[0m"
echo -e "\e[5mBlink\e[0m"
echo -e "\e[7mReverse (invert)\e[0m"
echo -e "\e[8mHidden\e[0m"
echo -e "\e[9mStrikethrough\e[0m"
# Combine attributes
echo -e "\e[1;3;31mBold italic red\e[0m"
Cursor Control
CSI sequences for cursor movement
# Move cursor
echo -e "\e[10A" # up 10 lines
echo -e "\e[5B" # down 5 lines
echo -e "\e[20C" # right 20 columns
echo -e "\e[3D" # left 3 columns
echo -e "\e[2;10H" # move to row 2, column 10
echo -e "\e[H" # move to home (1,1)
# Save and restore position
echo -e "\e[s" # save cursor position
echo -e "\e[u" # restore cursor position
echo -e "\e7" # save (DEC private)
echo -e "\e8" # restore (DEC private)
Screen Control
Clear and scroll
# Clear
echo -e "\e[2J" # clear entire screen
echo -e "\e[0J" # clear from cursor to end
echo -e "\e[1J" # clear from cursor to beginning
echo -e "\e[2K" # clear entire line
echo -e "\e[0K" # clear from cursor to end of line
# Scroll
echo -e "\e[3S" # scroll up 3 lines
echo -e "\e[3T" # scroll down 3 lines
# Alternative screen buffer (used by vim, less, htop)
echo -e "\e[?1049h" # switch to alt buffer
echo -e "\e[?1049l" # switch back to main buffer
OSC Sequences
Operating System Commands
# Set window title
echo -e "\e]0;My Terminal Title\a"
# Set clipboard (OSC 52) -- works over SSH
printf "\e]52;c;%s\a" "$(echo -n 'text to copy' | base64)"
# Hyperlinks (OSC 8)
echo -e "\e]8;;https://docs.domusdigitalis.dev\aClick here\e]8;;\a"
# Desktop notification (OSC 9 / OSC 777)
echo -e "\e]777;notify;Title;Body text\a"
Practical Scripts
Progress bar using escape sequences
progress_bar() {
local percent=$1
local width=40
local filled=$((percent * width / 100))
local empty=$((width - filled))
printf "\r\e[32m["
printf "%${filled}s" | tr ' ' '#'
printf "%${empty}s" | tr ' ' '-'
printf "] %3d%%\e[0m" "$percent"
}
for i in $(seq 0 5 100); do
progress_bar "$i"
sleep 0.1
done
echo
Check terminal color support
# 256-color test
for i in $(seq 0 255); do
printf "\e[48;5;%dm %3d \e[0m" "$i" "$i"
[ $(( (i + 1) % 16 )) -eq 0 ] && echo
done
# True color test
awk 'BEGIN{
for(r=0;r<256;r+=4){
printf "\033[48;2;%d;0;0m \033[0m",r
}
print ""
}'