如何将彩色文本输出到 Linux 终端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2616906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:56:42  来源:igfitidea点击:

How do I output coloured text to a Linux terminal?

c++linuxcolorsterminal

提问by Macha

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

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

How do I tell whether the terminal supports colour codes?

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

采纳答案by Thomas

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

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

Example:

例子:

 cout << "3[1;31mbold red text3[0m\n";

Here, \033is 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.

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

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 Wikipediafor other, less widely supported codes.

有关其他不太广泛支持的代码,请参阅维基百科上表格



To determine whether your terminal supports colour sequences, read the value of the TERMenvironment 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 colorscapability.

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

回答by Vlad

You can use escape sequences, if your terminal supports it. For example:

如果您的终端支持,您可以使用转义序列。例如:

echo \[3[32m\]Hello, \[3[36m\]colourful \[3[33mworld!3[0m\]

回答by Nick

The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string

最好的方法是使用 ncurses 库 - 尽管如果您只想输出一个简单的彩色字符串,这可能是一个敲碎坚果的大锤

回答by Alex

Before you going to output any color you need make sure you are in a terminal:

在输出任何需要的颜色之前,请确保您在终端中:

[ -t 1 ] && echo 'Yes I am in a terminal'  # isatty(3) call in C

Then you need to check terminal capability if it support color

然后你需要检查终端功能是否支持颜色

on systems with terminfo(Linux based)you can obtain quantity of supported colors as

在具有terminfo(基于 Linux)的系统上,您可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput colors)

on systems with termcap(BSD based)you can obtain quantity of supported colors as

在具有termcap(基于 BSD)的系统上,您可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput Co)

Then make you decision:

然后做你的决定:

[ ${Number_Of_colors_Supported} -ge 8 ] && {
    echo 'You are fine and can print colors'
} || {
    echo 'Terminal does not support color'
}


BTW, do not use coloring as it was suggested before with ESC characters. Use standard call to terminal capability that will assign you CORRECT colors that particular terminal support.

顺便说一句,不要像以前使用 ESC 字符所建议的那样使用着色。使用标准呼叫终端功能,该功能将为您分配特定终端支持的正确颜色。

基于BSD
fg_black="$(tput AF 0)"
fg_red="$(tput AF 1)"
fg_green="$(tput AF 2)"
fg_yellow="$(tput AF 3)"
fg_blue="$(tput AF 4)"
fg_magenta="$(tput AF 5)"
fg_cyan="$(tput AF 6)"
fg_white="$(tput AF 7)"
reset="$(tput me)"
基于 Linux
fg_black="$(tput setaf 0)"
fg_red="$(tput setaf 1)"
fg_green="$(tput setaf 2)"
fg_yellow="$(tput setaf 3)"
fg_blue="$(tput setaf 4)"
fg_magenta="$(tput setaf 5)"
fg_cyan="$(tput setaf 6)"
fg_white="$(tput setaf 7)"
reset="$(tput sgr0)"
用于
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"

回答by Christos Lytras

This is an old topic, but I wrote a class with nested subclasses and static members for colors defined by simple C macros.

这是一个老话题,但我编写了一个类,其中包含嵌套子类和由简单 C 宏定义的颜色的静态成员。

I got the colorfunction from this post Color Text In C Programmingin dreamincode.net by user no2pencil.

color从用户 no2pencil 在 dreamincode.net 中的C 编程中的彩色文本帖子中获得了该功能。

I made it this way so to be able to use the static constants in std::cout stream like this:

我这样做是为了能够像这样在 std::cout 流中使用静态常量:

cout << zkr::cc::fore::red << "This is red text. " 
     << zkr::cc::console << "And changing to console default colors, fg, bg."
     << endl;

The class and a test program source code can be downloaded here.

该类和一个测试程序源代码可以在这里下载。

cc::consolewill reset to console default colors and attributes, cc::underlinewill underline the text, which works on putty which I've tested the test program.

cc::console将重置为控制台默认颜色和属性,cc::underline将在文本下划线,该文本适用于我测试过的测试程序的腻子。

Colors:

颜色:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite

Which can be used with both foreand backstatic subclasses of the ccstatic class.

可以foreback静态类的子类和静态子cc类一起使用。

EDIT 2017

编辑 2017

I'm just adding the class code here to be more practical.

我只是在这里添加类代码更实用。

The color code macros:

颜色代码宏:

#define CC_CONSOLE_COLOR_DEFAULT "3[0m"
#define CC_FORECOLOR(C) "3[" #C "m"
#define CC_BACKCOLOR(C) "3[" #C "m"
#define CC_ATTR(A) "3[" #A "m"

and the main color function that defines a color or an attribute to the screen:

以及定义屏幕颜色或属性的主颜色函数:

char *cc::color(int attr, int fg, int bg)
{
    static char command[13];

    /* Command is the control command to the terminal */
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    return command;
}

ccolor.h

颜色文件

#include <stdio.h>

#define CC_CONSOLE_COLOR_DEFAULT "3[0m"
#define CC_FORECOLOR(C) "3[" #C "m"
#define CC_BACKCOLOR(C) "3[" #C "m"
#define CC_ATTR(A) "3[" #A "m"

namespace zkr
{
    class cc
    {
    public:

        class fore
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        class back
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        static char *color(int attr, int fg, int bg);
        static const char *console;
        static const char *underline;
        static const char *bold;
    };
}

ccolor.cpp

颜色文件

#include "ccolor.h"

using namespace std;

namespace zkr
{
    enum Color
    {
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        Default = 9
    };

    enum Attributes
    {
        Reset,
        Bright,
        Dim,
        Underline,
        Blink,
        Reverse,
        Hidden
    };

    char *cc::color(int attr, int fg, int bg)
    {
        static char command[13];
        /* Command is the control command to the terminal */
        sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
        return command;
    }

    const char *cc::console = CC_CONSOLE_COLOR_DEFAULT;
    const char *cc::underline = CC_ATTR(4);
    const char *cc::bold = CC_ATTR(1);

    const char *cc::fore::black = CC_FORECOLOR(30);
    const char *cc::fore::blue = CC_FORECOLOR(34);
    const char *cc::fore::red = CC_FORECOLOR(31);
    const char *cc::fore::magenta = CC_FORECOLOR(35);
    const char *cc::fore::green = CC_FORECOLOR(92);
    const char *cc::fore::cyan = CC_FORECOLOR(36);
    const char *cc::fore::yellow = CC_FORECOLOR(33);
    const char *cc::fore::white = CC_FORECOLOR(37);
    const char *cc::fore::console = CC_FORECOLOR(39);

    const char *cc::fore::lightblack = CC_FORECOLOR(90);
    const char *cc::fore::lightblue = CC_FORECOLOR(94);
    const char *cc::fore::lightred = CC_FORECOLOR(91);
    const char *cc::fore::lightmagenta = CC_FORECOLOR(95);
    const char *cc::fore::lightgreen = CC_FORECOLOR(92);
    const char *cc::fore::lightcyan = CC_FORECOLOR(96);
    const char *cc::fore::lightyellow = CC_FORECOLOR(93);
    const char *cc::fore::lightwhite = CC_FORECOLOR(97);

    const char *cc::back::black = CC_BACKCOLOR(40);
    const char *cc::back::blue = CC_BACKCOLOR(44);
    const char *cc::back::red = CC_BACKCOLOR(41);
    const char *cc::back::magenta = CC_BACKCOLOR(45);
    const char *cc::back::green = CC_BACKCOLOR(42);
    const char *cc::back::cyan = CC_BACKCOLOR(46);
    const char *cc::back::yellow = CC_BACKCOLOR(43);
    const char *cc::back::white = CC_BACKCOLOR(47);
    const char *cc::back::console = CC_BACKCOLOR(49);

    const char *cc::back::lightblack = CC_BACKCOLOR(100);
    const char *cc::back::lightblue = CC_BACKCOLOR(104);
    const char *cc::back::lightred = CC_BACKCOLOR(101);
    const char *cc::back::lightmagenta = CC_BACKCOLOR(105);
    const char *cc::back::lightgreen = CC_BACKCOLOR(102);
    const char *cc::back::lightcyan = CC_BACKCOLOR(106);
    const char *cc::back::lightyellow = CC_BACKCOLOR(103);
    const char *cc::back::lightwhite = CC_BACKCOLOR(107);
}

回答by BananaAcid

on OSX shell, this works for me (including 2 spaces in front of "red text"):

在 OSX shell 上,这对我有用(包括“红色文本”前面的 2 个空格):

$ printf "\e[033;31m  red text\n"
$ echo "$(tput setaf 1)  red text"

回答by Joel Sj?gren

Basics

基本

I have written a C++ class which can be used to set the foreground and background color of output. This sample program serves as an example of printing This ->word<- is red.and formatting it so that the foreground color of wordis red.

我编写了一个 C++ 类,可用于设置输出的前景色和背景色。此示例程序作为打印This ->word<- is red.和格式化的示例,使其前景色word为红色。

#include "colormod.h" // namespace Color
#include <iostream>
using namespace std;
int main() {
    Color::Modifier red(Color::FG_RED);
    Color::Modifier def(Color::FG_DEFAULT);
    cout << "This ->" << red << "word" << def << "<- is red." << endl;
}

Source

来源

#include <ostream>
namespace Color {
    enum Code {
        FG_RED      = 31,
        FG_GREEN    = 32,
        FG_BLUE     = 34,
        FG_DEFAULT  = 39,
        BG_RED      = 41,
        BG_GREEN    = 42,
        BG_BLUE     = 44,
        BG_DEFAULT  = 49
    };
    class Modifier {
        Code code;
    public:
        Modifier(Code pCode) : code(pCode) {}
        friend std::ostream&
        operator<<(std::ostream& os, const Modifier& mod) {
            return os << "3[" << mod.code << "m";
        }
    };
}

Advanced

先进的

You may want to add additional features to the class. It is, for example, possible to add the color magenta and even styles like boldface. To do this, just an another entry to the Codeenumeration. Thisis a good reference.

您可能希望向该类添加其他功能。例如,可以添加洋红色甚至粗体等样式。要做到这一点,只是Code枚举的另一个条目。是一个很好的参考。

回答by Uduse

try my header here for a quick and easy way to color text: Aedi's Color Header

在此处尝试我的标题,以快速简便地为文本着色:Aedi 的颜色标题



Escape-Sequence-Color-Header

转义序列颜色标题

Color Your Output in Unix using C++!!

使用 C++ 在 Unix 中为您的输出着色!!



Text Attribute Options:

文本属性选项:

ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED



Color Options:

颜色选项:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE



Format:

格式:

General Format, include value you want in $variable$

通用格式,在 $variable$ 中包含您想要的值

COLOR_$Foreground_Color$_$Background_Color$
COLOR_$Text_Attribute$_$Foreground_Color$_$Background_Color$
COLOR_NORMAL  // To set color to default

e.g.

例如

COLOR_BLUE_BLACK // Leave Text Attribute Blank if no Text Attribute appied
COLOR_UNDERSCORE_YELLOW_RED
COLOR_NORMAL



Usage:

用法:

Just use to stream the color you want before outputting text and use again to set the color to normal after outputting text.

只需在输出文本之前使用流式传输您想要的颜色,并在输出文本后再次使用将颜色设置为正常。

cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;

回答by gon1332

As others have stated, you can use escape characters. You can use my headerin order to make it easier:

正如其他人所说,您可以使用转义字符。您可以使用我的标题以使其更容易:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

使用标头宏的示例可能是:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

在此处输入图片说明

回答by Daniel Langr

I use the following solution, it's quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:

我使用以下解决方案,它非常简单和优雅,可以轻松粘贴到源代码中,并且适用于 Linux/Bash:

const std::string red("3[0;31m");
const std::string green("3[1;32m");
const std::string yellow("3[1;33m");
const std::string cyan("3[0;36m");
const std::string magenta("3[0;35m");
const std::string reset("3[0m");

std::cout << "Measured runtime: " << yellow << timer.count() << reset << std::endl;