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
- Using ANSI Escape Sequences
- Using the
tput
Command - Using the Terminfo Database
- 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"
-
\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
#!/bin/bash
RED=$(tput setaf 1)
RESET=$(tput sgr0)
echo "${RED}This text is red${RESET}"
Run the script:
bash colorchangingtext
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
#!/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
Run the script:
bash colorchange
4. Using Shell Functions for Reusability
Shell functions make color printing reusable and convenient.
Example:
Create a script:
vim color
#!/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"
Run the script:
bash color
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)