Course contentsShow
← Linux
Lesson 212 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Color-Coded Output Strategies

Improve human-readability of logs without sacrificing machine parsing.

In this lesson, you will learn how to use ANSI escape codes to make your terminal logs instantly readable for humans while ensuring they remain perfectly legible for automated parsing tools.

The Human-Machine Dilemma

When writing Bash scripts, you often face a conflict: you want your logs to be vibrant and easy to scan (e.g., bright red for errors, green for success), but you also need to feed those same logs into tools like grep, awk, or log aggregators. If you hard-code colors into your output, automated tools might see invisible escape sequences (like \033[31m) and get confused, potentially failing to identify patterns or keywords.

The Strategy: Conditional Logic

The professional approach is to define color variables that are only active when the output is directed to a terminal, and to strip them away when the output is redirected to a file or pipe.

Implementation Example

You can check if the current shell session is interactive using the [ -t 1 ] test, which checks if file descriptor 1 (stdout) is a terminal:

# Define color codes only if stdout is a terminal
if [ -t 1 ]; then
    RED='\033[0;31m'
    NC='\033[0m' # No Color
else
    RED=''
    NC=''
fi

# Usage in your script
echo -e "${RED}ERROR: Disk space critical!${NC}"

By setting the variables to empty strings when the output isn't a terminal, you ensure that scripts running in a CI/CD environment or piping to a log file remain clean and "machine-readable."

Best Practices

  1. Use Constants: Define your colors at the top of your script to keep your logic clean.
  2. Never Colorize Logs for Files: Always prioritize the "No Color" mode for logs intended for long-term storage or processing.
  3. Symbolic Indicators: Don't rely solely on color. Since some users may have color blindness or different terminal themes, always pair your colors with text markers (like [ERROR] or [SUCCESS]) so the information remains accessible without the visual styling.

Key Takeaway: Always use conditional logic to toggle ANSI codes so that your scripts provide a rich visual experience for users without breaking the data integrity for machine parsers.