Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shell script colours
## Colours and font styles
## Syntax: echo -e "${FOREGROUND_COLOUR}${BACKGROUND_COLOUR}${STYLE}Hello world!${RESET_ALL}"
# Escape sequence and resets
ESC_SEQ="\x1b["
RESET_ALL="${ESC_SEQ}0m"
RESET_BOLD="${ESC_SEQ}21m"
RESET_UL="${ESC_SEQ}24m"
# Foreground colours
FG_BLACK="${ESC_SEQ}30;"
FG_RED="${ESC_SEQ}31;"
FG_GREEN="${ESC_SEQ}32;"
FG_YELLOW="${ESC_SEQ}33;"
FG_BLUE="${ESC_SEQ}34;"
FG_MAGENTA="${ESC_SEQ}35;"
FG_CYAN="${ESC_SEQ}36;"
FG_WHITE="${ESC_SEQ}37;"
FG_BR_BLACK="${ESC_SEQ}90;"
FG_BR_RED="${ESC_SEQ}91;"
FG_BR_GREEN="${ESC_SEQ}92;"
FG_BR_YELLOW="${ESC_SEQ}93;"
FG_BR_BLUE="${ESC_SEQ}94;"
FG_BR_MAGENTA="${ESC_SEQ}95;"
FG_BR_CYAN="${ESC_SEQ}96;"
FG_BR_WHITE="${ESC_SEQ}97;"
# Background colours (optional)
BG_BLACK="40;"
BG_RED="41;"
BG_GREEN="42;"
BG_YELLOW="43;"
BG_BLUE="44;"
BG_MAGENTA="45;"
BG_CYAN="46;"
BG_WHITE="47;"
# Font styles
FS_REG="0m"
FS_BOLD="1m"
FS_UL="4m"
@anselmdk

This comment has been minimized.

Copy link

@anselmdk anselmdk commented Nov 24, 2014

Awesome - that's the first one that works for me in both linux and OSX! Would have loved to vote you up on stack overflow, but am having insufficient reputation points...

@ramiabraham

This comment has been minimized.

Copy link

@ramiabraham ramiabraham commented Jun 8, 2016

This rocks. Still using it today. Thanks for putting this together.

@woolinsilver

This comment has been minimized.

Copy link

@woolinsilver woolinsilver commented Sep 19, 2016

I don't believe this works as intended.
If, as per the usage example, you say:

echo -e "${FG_RED}${BG_CYAN}{FS_REG} hello world ${RESET_ALL}

then no style gets applied at all. The reason is that FS_REG causes all attributes, including colours, to be reset.
It will work as intended with this correction:

FS_REG="21;24m"

@ian128K

This comment has been minimized.

Copy link
Owner Author

@ian128K ian128K commented Jan 25, 2017

@woolinsilver Good catch! Thank you!

@danielloader

This comment has been minimized.

Copy link

@danielloader danielloader commented Nov 6, 2018

Does this work with printf? and if so, syntax example? Would like to use it with printfs column printing facilities.

@tavinus

This comment has been minimized.

Copy link

@tavinus tavinus commented Dec 27, 2018

@danielloader You can just use it on the first printf string since it escapes chars by default.

I have made something a bit different that supports each setting by itself and runs even on busybox/ash:
https://gist.github.com/tavinus/925c7c9e67b5ba20ae38637fd0e06b07
The script also prints examples for all vars defined.
(there is a commented line with a printf example there as well)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment