如何为 STDOUT 和 STDERR 设置字体颜色 [英] How to set font color for STDOUT and STDERR

查看:35
本文介绍了如何为 STDOUT 和 STDERR 设置字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想区分终端中的 STDOUT 和 STDERR 消息.如果脚本或命令在终端中打印消息,我想通过颜色进行区分;有可能吗?

I want to differentiate the STDOUT and STDERR messages in my terminal. If a script or command is printing a message in terminal I want to differentiate by colors; is it possible?

(例如 stderr 字体颜色为红色,stdout 字体颜色为蓝色.)

(E.g. stderr font color is red, and stdout font color is blue.)

示例(使用粗体):

$date
7 月 27 日星期三 12:36:50 IST 2011

$datee
bash:datee:找不到命令

$alias ls
别名 ls='ls --color=auto -F'

$aliass ls
bash: aliass: command not found

推荐答案

这是我想到的一个 hack,它似乎有效:

Here's a hack that I thought of and it seems to work:

给定以下别名以提高可读性:

Given the following aliases for readability:

alias blue='echo -en "\033[36m"'
alias red='echo -en "\033[31m"'
alias formatOutput='while read line; do blue; echo $line; red; done'

现在,您需要首先将终端中的字体颜色设置为红色(作为默认值,将用于 stderr).然后,运行您的命令并通过上面定义的 formatOutput 管道输出标准输出(它只是将每一行打印为蓝色,然后将字体颜色重置为红色):

Now, you need to first set the font color in your terminal to red (as the default, which will be used for stderr). Then, run your command and pipe the stdout through formatOutput defined above (which simply prints each line as blue and then resets the font color to red):

shell$ red
shell$ ls / somenonexistingfile | formatOutput

上面的命令将在 stderr 和 stdout 中打印,您会看到线条的颜色不同.

The above command will print in both stderr and stdout and you'll see that the lines are coloured differently.

希望能帮到你

更新:

为了使其可重复使用,我将其全部放在一个小脚本中:

To make this reusable, I've put it all in a small script:

$ cat bin/run 
#!/bin/bash
echo -en "\033[31m"  ## red
eval $* | while read line; do
    echo -en "\033[36m"  ## blue
    echo $line
    echo -en "\033[31m"  ## red
done
echo -en "\033[0m"  ## reset color

现在您可以将其与任何命令一起使用:

Now you can use this with any command:

$ run yourCommand

这篇关于如何为 STDOUT 和 STDERR 设置字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆