问题描述
Bash支持颜色,即\033[31m
切换为红色,而\033[0m
切换回无颜色.
Bash supports colors, i.e. \033[31m
switches to red and \033[0m
switches back to uncolored.
我想制作一个小型的bash包装器,将红色的stderr可靠地放出,即应该将\033[31m
放在stderr的后面,然后将\033[0m
放到stderr的后面.
I would like to make a small bash-wrapper that reliably puts out stderr in red, i.e. it should put \033[31m
before and \033[0m
after everything that comes from stderr.
我不确定这是否可能,因为当两个并行进程(甚至单个进程)同时向stdout和stderr写入时,就必须有一种方法来按字符逐个区分基础.
I'm not sure that this is even possible, because when two parallel processes (or even a single process) writes to both stdout and stderr there would have to be a way to distinguish the two by a character-by-character basis.
推荐答案
基于安德鲁顿的包装器
更改:
- 将stderr输出放回stderr
- 避免在行中使用
echo -e
处理内容
- Puts the stderr output back to stderr
- Avoid
echo -e
processing content in the lines
包装器
#!/bin/bash
"${@}" 2> >(
while read line; do
echo -ne "\033[31m" 1>&2
echo -n "${line}" 1>&2
echo -e "\033[0m" 1>&2
done
)
问题:输出线最终分组,而不是混合stdout/stderr
Issues:The output lines end up grouped, rather than mixed stdout/stderr
测试脚本:
#!/bin/bash
echo Hi
echo "\033[32mStuff"
echo message
echo error 1>&2
echo message
echo error 1>&2
echo message
echo error 1>&2
输出:
Hi
\033[32mStuff
message
message
message
error # <- shows up red
error # <- shows up red
error # <- shows up red
这篇关于bash包装纸将stderr颜色涂成红色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!