I am trying to have my stderr
be printed red in terminal. The below script redirects the 2
to a custom 8
upon debug trap.
exec 9>&2
exec 8> >(
while IFS='' read -r line || [ -n "$line" ]; do
echo -e "${RED}${line}${COLORRESET}"
done
)
function undirect(){ exec 2>&9; } # reset to original 9 (==2)
function redirect(){ exec 2>&8; } # set to custom 8
trap "redirect;" DEBUG
PROMPT_COMMAND='undirect;'
It comes from here, with a clear explanation.
Seems to work very fine, however non-newline-terminated input doesn't get printed out at all. Quoting the author gospes again:
bash> echo -en "hi\n" 1>&2
hi <-- this is red
bash> echo -en "hi" 1>&2
bash> echo -en "hi" 1>&2
bash> echo -en "hi\n" 1>&2
hihihi <-- this is red
I cannot figure out why. The non-newline content seems to end up in some kind of buffer. It either doesn't even reach the file descriptor 8
, or somehow doesn't want to be printed out right away. Where does it go? redirect
gets called properly every time. Also, IFS=''
means there is no delimiter, so i don't quite understand why the echoing out in 8
happens line-wise.
A bugfix would be much appreciated, I linked the quoted answer to this question.
This entire solution is, as pointed out by Gilles, not quite perfect. I am having issues with read, stdin, progress bars, can neither su
nor source
. And frequently major problems like broken pipes and unexpected terminal exits. If anybody got here by my linking, please do consider using https://github.com/sickill/stderred instead, it is much better (no problems yet) (however echo bla >&2
remains non-red and the respective issue is closed)