DEV Community

Adding colors to Bash scripts

Ifenna on November 23, 2019

I recently wrote a post-receive git hook for a server and I wanted to easily distinguish my hook's output from git information. This led me to look...
Collapse
 
moopet profile image
Ben Sinclair

Using escape codes directly is cool, but I'm a fan of using tput like this:

# SET Attribute Foreground <colour 123>
kindalightblue=$(tput setaf 123)
Enter fullscreen mode Exit fullscreen mode

There are a lot of handy things tput can do, and though the capabilities vary with your terminal, and though it's not completely portable either, you get all the colours your terminal can show.

Collapse
 
ifenna__ profile image
Ifenna • Edited

I haven't heard about tput before. I'll definitely check it out.

EDIT: Just took a look. It's great. Thanks for the tip 🚀.

Collapse
 
jianwu profile image
jianwu

Thanks for the great article. However in my environment, if I run the example, it will print the escape code literally. e.g.

$ echo -e "\e[32mRed text\e[0m"
\e[32mRed text\e[0m
Enter fullscreen mode Exit fullscreen mode

For me the solution is to use printf, e.g.

echo -e $(printf "\e[32mRed text\e[0m")`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
toransahu profile image
Toran Sahu

Try $ echo -e "\033[32mRed text\e[0m"
\e[32mRed text\033[0m
. i.e. \033 instead \e.

Collapse
 
sombody101 profile image
Sombody101

Try using -ne rather than -e.

Collapse
 
absoftware profile image
Ariel Bogdziewicz

This helped me as well in macOS. Thank you!

Collapse
 
laakkus profile image
laakkus • Edited

I have RED already in use, so had to do this:

    NORMAL=0
    BOLD=1
    FAINT=2
    ITALIC=3
    UNDERLINE=4
    RED='\033[0;31m'
    ITALICRED=$(echo $RED|sed -e "s/\[./\[${ITALIC}/")
    FAINTRED=$(echo $RED|sed -e "s/\[./\[${FAINT}/")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
keithy profile image
Keith • Edited
bgreen () { printf "\e[1m\e[32m" ; $@ ; printf "\e[0m"; }
red    () { printf      "\e[31m" ; $@ ; printf "\e[0m"; }

bgreen echo "Am I green?"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dtmilano profile image
Diego Torres Milano

If you want to see the colors you can use this script: gist.github.com/dtmilano/4055d6df5... which uses tput.

Collapse
 
placidrod profile image
Placid Rodrigues

Thank you for the super helpful post.
I think the first example should be: echo -e "\e[31mRed text\e[0m"
32 represents green.

Collapse
 
johnnyxbell profile image
Johnny Bell

Great article. Something that should be simple but is actually super hard to understand thank you

Collapse
 
ifenna__ profile image
Ifenna

Glad to help.

Collapse
 
kubeden profile image
Kuberdenis

Great post!

Collapse
 
kognianov profile image
Kliment Ognianov

Just add '5' as a blinking special, non-colour code ;)

Collapse
 
ifenna__ profile image
Ifenna

Thanks for noticing! Fixed it.