bash: print stderr in red color
Is there a way to make bash display stderr messages in red color?
command 2> >(while read line; do echo -e "\e[01;31m$line\e[0m" >&2; done)
Method 1: Use process substitution directly:
command 2> >(sed $'s,.*,\e[31m&\e[m,'>&2)
Method 2: Create a function in bash or zsh :
color()(set -o pipefail;"$@" 2> >(sed $'s,.*,\e[31m&\e[m,'>&2))
Use it like this:
$ color command
Both methods will show the command's stderr
in red.
Keep reading for an explanation of how it works. There are some interesting features demonstrated by these commands. The first 3 bullet points only apply to Method 2. The rest apply to both methods.
-
color()...
— Creates a bash function called color. -
set -o pipefail
— This is a shell option that preserves the error return code of a command whose output is piped into another command. This is done in a subshell, which is created by the parentheses, so as not to change the pipefail option in the outer shell. -
"$@"
— Executes the arguments to the function as a new command."$@"
is equivalent to"$1" "$2" ...
-
2> >(...)
— The>(...)
syntax is called process substitution. Preceded by2>
, it connects thestderr
of the main command to thestdin
of thesed
process inside the parentheses. -
sed ...
— Because of the redirects above,sed
'sstdin
is thestderr
of the executed command. Its function is to surround each line with color codes. -
$'...'
A bash construct that causes it to understand backslash-escaped characters -
.*
— Matches the entire line. -
\e[31m
— The ANSI escape sequence that causes the following characters to be red -
&
— Thesed
replace character that expands to the entire matched string (the entire line in this case). -
\e[m
— The ANSI escape sequence that resets the color. -
>&2
— Shorthand for1>&2
, this redirectssed
'sstdout
tostderr
.