Introduction
Shell scripts can be made more readable by adding color to they output. This is achieved by embedding ANSI escape codes direct into the output stream. These codes are interpreted by most modern terminals to change text attributes like color. Below is a comprehensive guide on how to implement colored logging in a Bash script.
Complete Script: colorful\_logging.sh
#!/bin/bash
# Define color codes using ANSI escape sequences
COLOR_RED='\033[0;31m'
COLOR_GREEN='\033[0;32m'
COLOR_YELLOW='\033[0;33m'
COLOR_BLUE='\033[0;34m'
COLOR_RESET='\033[0m' # Resets all attributes to default
# Function to print error messages in red
print_error() {
echo -e "${COLOR_RED}[ERROR] $1${COLOR_RESET}"
}
# Function to print warning messages in yellow
print_warning() {
echo -e "${COLOR_YELLOW}[WARNING] $1${COLOR_RESET}"
}
# Function to print informational messages in green
print_info() {
echo -e "${COLOR_GREEN}[INFO] $1${COLOR_RESET}"
}
# Function to print debug messages in blue
print_debug() {
echo -e "${COLOR_BLUE}[DEBUG] $1${COLOR_RESET}"
}
# Example function to showcase different log levels
demonstrate_logging() {
print_info "Initiating demonstration function..."
print_debug "This is a detailed debug message for troubleshooting."
# Simulate an operation based on the provided argument
case "$1" in
"failure")
print_error "Operation failed. This is a simulated error condition."
;;
"success")
print_info "Operation completed successfully."
;;
*)
print_warning "Unknown argument provided: '$1'. Defaulting to success."
print_info "Operation completed successfully."
;;
esac
print_warning "This is a cautionary message, indicating a potential issue."
}
# Main script execution block
run_script() {
print_info "Script execution started..."
# Call the example function with different scenarios
demonstrate_logging "success"
demonstrate_logging "failure"
demonstrate_logging "invalid"
print_info "Script execution finished."
}
# Execute the main function
run_script
Explanation
- Color Definitions: The script begins by defining variables for different colors using standard ANSI escape sequences. The
COLOR_RESETvarible is crucial as it prevents subsequent text from being colored. - Logging Functions: Separate functions (
print_error,print_warning, etc.) are created for each log level. Each function usesecho -eto enable interpretation of the escape sequences and appends the reset code to ensure the terminal returns to its default state. - Example Logic: The
demonstrate_loggingfunction takes an argument and uses acasestatement to simulate different outcomes, calling the appropriate logging function for each scenario. - Execution: The
run_scriptfunction serves as the entry point, orchestrating the calls to the example function and providing a clear start and end message.
Running the Script
- Save the code as
colorful_logging.sh. - Make the script executable: ```
chmod +x colorful_logging.sh
- Execute the script: ```
./colorful_logging.sh
Expected Output
When run, the script will produce output with colored text for different log levels, making it easier to distinguish between errors, warnings, and informational messages at a glance.
Considerations
- Terminal Support: Ensure your terminal application supports ANSI color codes. Most modern terminals, including those on Linux, macOS, and Windows, do.
- Log Levels: You can easily extend this by adding more log levels (e.g.,
FATAL,TRACE) or by implementing a mechanism to disable certain levels (likeDEBUG) in a production environment. - Enhancements: For more advanced use cases, consider adding timestamps to each log entry or redirecting output to both the console and a log file.