Colored Text Output in Linux Shell and Bash Scripts

This script is used in a lot of other scripts I produce over time, and it’s very handy for generating colored text output in the terminal.

Example of usage

Here’s an example of using the colors.sh script:

#!/bin/bash
source colors.sh
echo "${fg_yellow}Yellow ${fg_reset}Normal ${fg_green}Green {$fg_reset}";

Download

You can view or download the script here:

https://invision-web.net/web/sources/colors.sh

Or obtain it from shell:

wget -qO- https://invision-web.net/web/sources/colors.sh > colors.sh
chmod +x colors.sh

colors.sh

#!/bin/bash
# coloring the shell text
while getopts "h?" opt; do
    case "$opt" in
    h|\?)
		echo "Script with colors (fg_black , fg_red , fg_yellow , ... , fg_reset)"
        echo "Usage:"		
        echo "source $0 # to include in bash script"
		echo "echo \${fg_colorname} ; {command} ; echo \${fg_reset} ";
		
        exit 0
        ;;    
    esac
done

#################################################################################

export fg_black="$(tput setaf 0)"
export fg_red="$(tput setaf 1)"
export fg_green="$(tput setaf 2)"
export fg_yellow="$(tput setaf 3)"
export fg_blue="$(tput setaf 4)"
export fg_magenta="$(tput setaf 5)"
export fg_cyan="$(tput setaf 6)"
export fg_white="$(tput setaf 7)"
export fg_reset="$(tput sgr0)"
Linux Shell / Bash Scripting, Open Source, Tutorials | Posted on July 2, 2013 by .

About Kristijan Burnik

Kristijan Burnik is a Programmer and Web Developer specializing in Server-side and Client-side Technologies and Application Development on Linux Servers and Windows Desktop . Also has experience in Networking, Desktop application development as well as Android mobile application development . Experienced in Programming Languages like Java, C, C++, C#, PHP, Javascript, MySQL and somewhat in other languages like Bash, Perl & Python. Sometimes he works as a Graphical Designer for digital production as well as for printing and advertising. He dedicates his spare time writing Tech Articles on his blog in order to share his work with others, as well as to document his projects for his own use. He's also an Educator & Mentor in field of Algorithms and Programming to young programmers in Zagreb, Croatia.

Leave a Reply