如何将彩色文本输出到 Linux 终端? [英] How do I output coloured text to a Linux terminal?

查看:38
本文介绍了如何将彩色文本输出到 Linux 终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将彩色字符打印到支持它的 Linux 终端?

How do I print coloured characters to a Linux terminal that supports it?

如何判断终端是否支持色码?

How do I tell whether the terminal supports colour codes?

推荐答案

你需要输出ANSI颜色代码.请注意,并非所有终端都支持此功能;如果不支持颜色序列,则会显示垃圾.

You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.

示例:

 cout << "33[1;31mbold red text33[0m
";

这里,33 是 ESC 字符,ASCII 27.后面是 [,然后是零个或多个由 ; 分隔的数字,最后是字母 m.数字描述了从那时起要切换到的颜色和格式.

Here, 33 is the ESC character, ASCII 27. It is followed by [, then zero or more numbers separated by ;, and finally the letter m. The numbers describe the colour and format to switch to from that point onwards.

前景色和背景色的代码是:

The codes for foreground and background colours are:

         foreground background
black        30         40
red          31         41
green        32         42
yellow       33         43
blue         34         44
magenta      35         45
cyan         36         46
white        37         47

此外,您可以使用这些:

Additionally, you can use these:

reset             0  (everything back to normal)
bold/bright       1  (often a brighter shade of the same colour)
underline         4
inverse           7  (swap foreground and background colours)
bold/bright off  21
underline off    24
inverse off      27

请参阅维基百科上的表格,了解其他支持较少的代码.

See the table on Wikipedia for other, less widely supported codes.

要确定您的终端是否支持颜色序列,请读取 TERM 环境变量的值.它应该指定使用的特定终端类型(例如 vt100gnome-terminalxtermscreen、...)然后在 terminfo 数据库 中查找;检查 colors 功能.

To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.

这篇关于如何将彩色文本输出到 Linux 终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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