DEV Community

Avnish
Avnish

Posted on

How to Print Colored Text to the Linux Terminal

Printing colored text can improve readability, highlight important information, and enhance aesthetics in your terminal applications. Here's how to achieve this using various methods:


Table of Contents

  1. Using ANSI Escape Sequences
  2. Using the tput Command
  3. Using the Terminfo Database
  4. Using Shell Functions for Reusability

1. Using ANSI Escape Sequences

ANSI escape sequences provide a straightforward way to apply color formatting.

Example:

echo -e "\e[31mThis text is red\e[0m"
Enter fullscreen mode Exit fullscreen mode
  • \e[31m: Sets the text color to red.
  • \e[0m: Resets formatting to default.

Common ANSI Color Codes:

Code Color
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan

2. Using the tput Command

tput leverages terminal capabilities to set colors dynamically.

Example:

Create a script:

vim colorchangingtext
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash
RED=$(tput setaf 1)
RESET=$(tput sgr0)
echo "${RED}This text is red${RESET}"
Enter fullscreen mode Exit fullscreen mode

Run the script:

bash colorchangingtext
Enter fullscreen mode Exit fullscreen mode

Color Codes for tput:

Code Color
0 Black
1 Red
2 Green
3 Yellow
4 Blue
5 Magenta
6 Cyan
7 White

3. Using the Terminfo Database

The terminfo database ensures compatibility by detecting terminal color support.

Example:

Create a script:

vim colorchange
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash
if [ $(tput colors) -ge 8 ]; then
  RED=$(tput setaf 1)
  RESET=$(tput sgr0)
  echo "${RED}This text is red${RESET}"
else
  echo "Terminal does not support colors."
fi
Enter fullscreen mode Exit fullscreen mode

Run the script:

bash colorchange
Enter fullscreen mode Exit fullscreen mode

4. Using Shell Functions for Reusability

Shell functions make color printing reusable and convenient.

Example:

Create a script:

vim color
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash
print_color() {
  local color=$1
  local text=$2
  echo -e "$(tput setaf $color)$text$(tput sgr0)"
}

# Usage
print_color 2 "This text is green"
Enter fullscreen mode Exit fullscreen mode

Run the script:

bash color
Enter fullscreen mode Exit fullscreen mode

Conclusion

By utilizing ANSI escape sequences, tput, or the terminfo database, you can create visually appealing terminal outputs. Shell functions add reusability and modularity to your scripts. Experiment with these methods to identify what works best for your needs.

Top comments (0)