To add a background color to your echo statements in a Bash script, you can use ANSI escape codes for text formatting, just like you did for text color. In this case, you’ll use codes for background colors. Here’s an example of how you can do it:
#!/bin/bash # Text colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' NC='\033[0m' # No Color # Background colors BG_RED='\033[41m' BG_GREEN='\033[42m' BG_YELLOW='\033[43m' BG_NC='\033[0m' # Reset background color # Usage: color_echo COLOR BACKGROUND MESSAGE color_echo() { local color="$1" local bg_color="$2" shift 2 local message="$@" echo -e "${color}${bg_color}${message}${NC}${BG_NC}" } # Example usage color_echo $RED $BG_GREEN "Red text on green background." color_echo $GREEN $BG_YELLOW "Green text on yellow background." color_echo $YELLOW $BG_RED "Yellow text on red background."
In this example, background colors are achieved using ANSI escape codes like \033[41m for a red background. The color_echo function is updated to take both a text color code and a background color code as arguments, along with the message to display.
Remember that the effectiveness of background colors can depend on your terminal emulator’s settings and compatibility. Additionally, consider the contrast between the text color and the background color to ensure readability.
As with text colors, you can customize the background color codes and the color_echo function to match your preferences and requirements.