Skip to content

Instantly share code, notes, and snippets.

@Robert-96
Last active July 12, 2022 21:55
Show Gist options
  • Save Robert-96/0281c940b2c105392489c567bf12c445 to your computer and use it in GitHub Desktop.
Save Robert-96/0281c940b2c105392489c567bf12c445 to your computer and use it in GitHub Desktop.
ANSI Color Sequences

ANSI Escape Sequences

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on terminals.

Constants

Add ANSI Escape Sequences to style your output in different colors and formats using a set of predefined variables.

#!/bin/sh

ESC="\033"
RESET="${ESC}[0m"

BLACK_FG="${ESC}[30m"
RED_FG="${ESC}[31m"
GREEN_FG="${ESC}[32m"
YELLOW_FG="${ESC}[33m"
BLUE_FG="${ESC}[34m"
PURPLE_FG="${ESC}[35m"
CYAN_FG="${ESC}[36m"
WHITE_FG="${ESC}[37m"

BLACK_BG="${ESC}[40m"
READ_BG="${ESC}[41m" 
GREEN_BG="${ESC}[42m"
YELLOW_BG="${ESC}[43m" 
BLUE_BG="${ESC}[44m" 
PURPLE_BG="${ESC}[45m" 
CYAN_BG="${ESC}[46m" 
WHITE_BG="${ESC}[47m"

BOLD_ON="${ESC}[1m"
BOLD_OFF="${ESC}[22m"
ITALIC_ON="${ESC}[3m"
ITALIC_OFF="${ESC}[23m"
UNDERLINE_ON="${ESC}[4m"
UNDERLINE_OFF="${ESC}[24m"
INVERSE_ON="${ESC}[7m"
INVERSE_OFF="${ESC}[27m"

Color names that end with 'FG' are foreground colors, and those ending with 'BG' are background colors.

How it works?

echo "${PURPLE_BG}This is a phrase in purple.${RESET}"
echo "${YELLOW_BG}This is a phrase with yellow background.${RESET}"
echo "${BOLD_ON}This is bold${BOLD_OFF} and ${ITALIC_ON}this is italic.${ITALIC_OFF}"
echo "${BOLD_ON}this is in bold and ${ITALIC_ON}this is italic${ITALIC_OFF}within the bold${RESET}"
echo "${UNDERLINE_ON}This is underlined${UNDERLINE_OFF} and this is not."

Functions

#!/bin/sh

success() {
    echo "${GREEN_BG}$1${RESET}"
}

info() {
    echo "${BLUE_FG}$1${RESET}"
}

warning() {
    echo "${YELLOW_FG}$1${RESET}"
} 

error() {
    echo "${READ_FG}$1${RESET}"
}

How it works?

#!/bin/sh
ESC="\033"
RESET="${ESC}[0m"
BLACK_FG="${ESC}[30m"
RED_FG="${ESC}[31m"
GREEN_FG="${ESC}[32m"
YELLOW_FG="${ESC}[33m"
BLUE_FG="${ESC}[34m"
PURPLE_FG="${ESC}[35m"
CYAN_FG="${ESC}[36m"
WHITE_FG="${ESC}[37m"
BLACK_BG="${ESC}[40m"
READ_BG="${ESC}[41m"
GREEN_BG="${ESC}[42m"
YELLOW_BG="${ESC}[43m"
BLUE_BG="${ESC}[44m"
PURPLE_BG="${ESC}[45m"
CYAN_BG="${ESC}[46m"
WHITE_BG="${ESC}[47m"
BOLD_ON="${ESC}[1m"
BOLD_OFF="${ESC}[22m"
ITALIC_ON="${ESC}[3m"
ITALIC_OFF="${ESC}[23m"
UNDERLINE_ON="${ESC}[4m"
UNDERLINE_OFF="${ESC}[24m"
INVERSE_ON="${ESC}[7m"
INVERSE_OFF="${ESC}[27m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment