When working with terminal output, differentiating between stdout and stderr quickly becomes crucial - especially in complex scripts or when debugging. The default monochrome output makes it challenging to spot errors immediately.
Bash supports ANSI color codes which we can leverage:
echo -e "\e[31mThis text is red\e[0m"
Add this to your .bashrc
or .bash_profile
:
exec 9>&2 exec 8> >( while IFS='' read -r line || [[ -n "$line" ]]; do echo -e "\033[31m${line}\033[0m" done ) exec 2>&8
For one-time use in scripts:
command 2> >(while read line; do echo -e "\e[01;31m$line\e[0m" >&2; done)
Verify it works with:
# Generate both stdout and stderr (echo "Normal output"; ls /nonexistent 2>&1)
For more sophisticated formatting:
exec 2> >(while read -r line; do printf "\033[1;31m[ERROR]\033[0m \033[31m%s\033[0m\n" "$line" >&2 done)
Remember:
- Color codes might not work in all terminals
- Some programs handle their own stderr formatting
- Consider adding color toggles for CI/CD environments
When working in terminal environments, distinguishing between standard output (stdout) and standard error (stderr) can significantly improve debugging efficiency. By default, both streams appear identical, making it harder to spot errors quickly.
The simplest method to color stderr red involves creating a wrapper function that processes the output streams separately:
exec 2> >(while read line; do echo -e "\e[31m$line\e[0m" >&2; done)
This command redirects stderr (file descriptor 2) through a process substitution that prepends red color codes to each line.
For a permanent solution, add this to your ~/.bashrc
:
color_stderr() { exec 2> >(while read -r line; do printf "\033[1;31m%s\033[0m\n" "$line" >&2 done) } # Enable by default or call manually color_stderr
For more control, you can filter specific error patterns:
color_stderr() { exec 2> >(while read -r line; do if [[ $line == *"error"* ]]; then printf "\033[1;31m%s\033[0m\n" "$line" >&2 else printf "\033[33m%s\033[0m\n" "$line" >&2 fi done) }
Verify your setup works with these test commands:
# Generate stdout echo "This is normal output" # Generate stderr ls /nonexistent 2>/dev/null || echo "Simulated error" >&2
- Process substitution (
>(command)
) may not work in all shells - Color codes might interfere with some terminal applications
- The solution adds slight overhead to error output processing
For systems where process substitution isn't available:
# Simple alias for common commands alias make='make 2>&1 | grep --color=always -E "^|error"'