How To Change the Color of the Output in Linux Bash?

Published June 22, 2024

Problem: Customizing Bash Output Colors

Linux Bash users often want to change the color of their terminal output. This can make the command-line interface look better and help tell different types of information apart. Many users don't know how to change these colors in the Bash environment. Changing output colors can make text easier to read and create a more personal command-line experience.

Solution: Methods to Change Bash Output Color

Using ANSI Escape Sequences

ANSI escape sequences are codes that control text formatting in terminals. These sequences start with the escape character (\033 or \e) followed by square brackets and numbers for colors.

Basic syntax for changing text color:

\033[COLORm

Replace COLOR with a number from 30 to 37 for text colors: 30 (black), 31 (red), 32 (green), 33 (yellow), 34 (blue), 35 (magenta), 36 (cyan), 37 (white)

Using the echo Command with Color Codes

The echo command with the -e option lets you use escape sequences in your output.

Example:

echo -e "\033[31mThis text is red\033[0m"

Here, \033[31m sets the text color to red, and \033[0m resets it to the default.

More examples:

echo -e "\033[32mGreen text\033[0m"
echo -e "\033[34mBlue text\033[0m"
echo -e "\033[33mYellow text\033[0m"

Using tput for Color Manipulation

The tput command provides a way to change text colors in scripts.

Basic syntax for setting text color:

tput setaf COLOR_NUMBER

COLOR_NUMBER ranges from 0 to 7: 0 (black), 1 (red), 2 (green), 3 (yellow), 4 (blue), 5 (magenta), 6 (cyan), 7 (white)

Example:

tput setaf 1; echo "Red text"; tput sgr0

Here, tput sgr0 resets the text formatting.

To set background color, use setab instead of setaf:

tput setab 3; echo "Text with yellow background"; tput sgr0

These methods offer ways to add color to your Bash output, improving readability of your terminal interface.

For more information on ANSI escape codes, you can refer to the ANSI escape code article.

To learn more about the tput command, check out the Linux manual page for tput.

Advanced Techniques for Colorful Bash Scripts

Creating Color Variables for Consistent Usage

Define color variables in scripts to keep your code readable. Here's how to create color variables:

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

Use these variables in your scripts:

echo -e "${RED}This is red text${NC}"
echo -e "${GREEN}This is green text${NC}"

Benefits of using variables for color management:

  • Easy to change colors in the script
  • Improves code readability
  • Reduces errors from typing color codes often

Combining Colors and Text Styles

Add bold, underline, and other text attributes to create eye-catching output:

Bold text:

echo -e "\033[1mThis is bold text\033[0m"

Underlined text:

echo -e "\033[4mThis is underlined text\033[0m"

Combining colors and styles:

echo -e "\033[1;31mThis is bold red text\033[0m"

You can create variables for these combinations:

BOLD_RED='\033[1;31m'
UNDERLINE_BLUE='\033[4;34m'

echo -e "${BOLD_RED}Bold red text${NC}"
echo -e "${UNDERLINE_BLUE}Underlined blue text${NC}"

These techniques allow you to create visually appealing and informative Bash scripts.

For more information on Bash scripting, check out the GNU Bash Manual.

Best Practices for Colorizing Bash Output

Compatibility Across Different Terminals

When using colors in Bash scripts, consider compatibility across different terminals and operating systems:

  • Use ANSI escape codes or tput commands, which work on most Linux distributions and macOS.
  • Avoid color codes specific to certain terminals.
  • Test your scripts on different systems to check color display.
  • Use a color library that handles compatibility issues for you.

Here's an example of a compatible color setting:

if [ -t 1 ]; then
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    RESET=$(tput sgr0)
else
    RED=""
    GREEN=""
    RESET=""
fi

echo "${RED}This should be red on most terminals${RESET}"

Resetting Colors to Maintain Readability

After using colored output, it's important to reset the colors to their default values:

  • Reset colors after each colored output to avoid affecting later text.
  • Use the reset command at the end of colored sections.
  • Use a trap to reset colors if the script exits unexpectedly.

Here are some methods to reset text color and attributes:

  1. Using ANSI escape code:

    echo -e "\033[0mThis resets all attributes"
  2. Using tput:

    echo "$(tput sgr0)This also resets all attributes"
  3. Using a variable (recommended for consistency):

    RESET='\033[0m'
    echo -e "${RED}Red text${RESET} Normal text"

By following these practices, you can create scripts with colored output that work on different systems and maintain readability throughout execution.

Alternative Approaches to Colorizing Bash Output

Using 'printf' for Formatted Color Output

The printf command offers more control over output formatting than echo. It's useful for color formatting in Bash scripts.

Benefits of printf over echo:

  • Better control over output formatting
  • Consistent behavior across Bash versions
  • Allows for field width specification and alignment

Examples of color formatting with printf:

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

printf "${RED}%-20s${NC} ${GREEN}%s${NC}\n" "Error:" "File not found"
printf "${RED}%-20s${NC} ${GREEN}%s${NC}\n" "Warning:" "Low disk space"

This code creates aligned, colored output for error and warning messages.

Third-Party Color Libraries

Some third-party color libraries are available for Bash, offering pre-defined color functions and simpler syntax.

Available color libraries:

  • Bash-it: A collection of community Bash commands and scripts
  • bashcopy: A small library for colored output in Bash scripts
  • ansi: A library for ANSI escape codes in shell scripts

Pros of using external libraries:

  • Pre-defined color functions for quick implementation
  • Often include extra formatting options
  • May handle terminal compatibility issues

Cons of using external libraries:

  • Extra dependency for your scripts
  • May be too much for simple color needs
  • Possible compatibility issues with different Bash versions

Example using the 'colors.sh' library:

source colors.sh

echo "$(red "This is red text")"
echo "$(green "This is green text")"

While these libraries can simplify color usage, consider your needs and script complexity when deciding whether to use them.

To explore Bash color libraries, check out Bash-it on GitHub.

Troubleshooting Color Issues in Bash

Fixing Uninterpreted Color Codes

Color codes may not work in Bash scripts for these reasons:

  • The terminal doesn't support color codes
  • The -e option is missing when using echo
  • Wrong syntax in color codes
  • Color support is off in the terminal

Ways to fix color sequence problems:

  1. Check terminal color support:

    if [ -t 1 ]; then
    echo "Terminal supports colors"
    else
    echo "Terminal does not support colors"
    fi
  2. Use echo with the -e option:

    echo -e "\033[31mRed text\033[0m"
  3. Check color code syntax:

    
    # Right syntax
    echo -e "\033[31mRed text\033[0m"

Wrong syntax

echo -e "\033[31Red text\033[0m"


4. Use tput for better compatibility:
```bash
red=$(tput setaf 1)
reset=$(tput sgr0)
echo "${red}Red text${reset}"

Fixing Color Differences Across Terminals

Terminals may show colors differently. To fix these differences:

  1. Use standard ANSI color codes (30-37 for foreground, 40-47 for background)

  2. Test your scripts on different terminals

  3. Use color libraries that fix compatibility issues

  4. Add an option to turn off colors in your scripts:

use_color=true

if [ "$use_color" = true ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    NC='\033[0m'
else
    RED=''
    GREEN=''
    NC=''
fi

echo -e "${RED}This might be red${NC}"
echo -e "${GREEN}This might be green${NC}"
  1. Use tput for more consistent output:
if [ -t 1 ]; then
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    RESET=$(tput sgr0)
else
    RED=""
    GREEN=""
    RESET=""
fi

echo "${RED}This should be consistently red${RESET}"
echo "${GREEN}This should be consistently green${RESET}"

These methods can help you fix color issues and create consistent colored output in your Bash scripts across different terminals.