Color output in console

This page was created to consolidate colorization of CLI outputs.

Background

Escape sequences

The ANSI escape sequences define a way to put additional information into terminal output, and color is part of this "additional information". Throughout the years the range of terminal colors has been vastly expanded, from the initial eight colors to a full 24-bit truecolor.

The basic color encoding provides 8 normal-brightness colors and 8 brighter versions of these colors. Modern terminal emulators, including the Linux console itself, allows you to specify the precise RGB values that the colors translate to. This mode is supported by almost all terminal emulators.

With the advent of 256-color displays came the 256-color escape. The 256 colors are the 16 basic colors, the 216 RGB colors (laid out in a 6x6x6 cube), and 24 levels of greyscale. Except for the first 16 colors, the scheme is usually not customizable as it has a well-defined mapping to RGB. This mode is supported by most terminal emulators. (A minority of emulators use a similar but incompatible encoding with only 88 colors. You are very unlikely to use them in practise, but they will appear in the terminfo database.)

Less commonly supported is the truecolor mode, allowing one to use 16.7 million (224) colors in RGB (each value ranging from 0 to 255).

Termcap and terminfo

Termcap and terminfo, part of ncurses, are databases that provide information on the escape sequences terminals (usually specified by the TERM env-var) understand. The tput(1) and infocmp(1) commands can be used to access them from command-line.

Applications

diff

diffutils from version 3.4 includes the option (GNU mailing list).

$ alias diff='diff --color=auto'

grep

The option enables color highlighting. Color codes are emitted only on standard output; not in pipes or redirection.

Color output in grep is also useful with regexp tasks.

Use an alias to permanently enable this option:

alias grep='grep --color=auto'

The variable is used to define colors, and it configures various parts of highlighting. To change the colors, find the needed ANSI escape sequence and apply it. See for more information.

The -n option includes file line numbers in the output.

ip

command from iproute2 supports colors with  option. You can use an alias to enable colored output. When using  parameter, colored output will be enabled only when stdout is a terminal.
 alias ip='ip -color=auto'

Environment variables

As with the #man case, we can tell less to emit colors when it is meaning to make bold text and other formatting effects.

Add the following lines to your shell configuration file:

export LESS='-R --use-color -Dd+r$Du+b'

It will set red for bold and blue for underlined.

For more information about the and options, see or .

Reading from stdin

When you run a command and pipe its standard output (stdout) to less for a paged view (e.g. ), you may find that the output is no longer colored. This is usually because the program tries to detect if its stdout is an interactive terminal, in which case it prints colored text, and otherwise prints uncolored text. This is good behaviour when you want to redirect stdout to a file, e.g. pacman -Qe > pkglst-backup.txt, but less suited when you want to view output in less.

Some programs provide an option to disable the interactive tty detection:

# dmesg --color=always | less

In case that the program does not provide any similar option, it is possible to trick the program into thinking its stdout is an interactive terminal with the following utilities:

Example:
    Example:

    Alternatively, using zpty module from zsh:

    Usage:

    $ ptyless program

    To pipe it to other pager (less in this example):

    $ pty program | less

    ls

    The option enables color highlighting. Color codes are emitted only on standard output; not in pipes or redirection.

    Use an alias to permanently enable this option:

    alias ls='ls --color=auto'

    The variable is used to define colors, and it configures various parts of highlighting. Use the command to set it.

    An advanced alternative to dircolors that ships with many themes is the vivid package, see for usage.

    See ls(1) for more information.

    man

    There is a real color facility in , but it is strongly discouraged for man pages. Here we fake a colored by hacking two main pagers, and : we replace the sequences for bold, standout, and underline with spiced ones that contain color.

    Using bat

    can be used as a colorizing pager for man, by setting the  environment variable

    as documented here.

    Using less

    See #less for a more detailed description.

    export MANPAGER="less -R --use-color -Dd+r -Du+b"

    For Fish you could accomplish this with:

    ~/.config/fish/config.fish
    set -xU MANPAGER 'less -R --use-color -Dd+r -Du+b'

    Remember to source your config or restart your shell to make the changes take effect.

    Using most

    The basic function of 'most' is similar to and , but it has a smaller feature set. Configuring most to use colors is easier than using less, but additional configuration is necessary to make most behave like less. Install the package.

    Edit , uncomment the pager definition and change it to:

    DEFINE     pager     most -s

    Test the new setup by typing:

    $ man whatever_man_page

    Modifying the color values requires editing ~/.mostrc (creating the file if it is not present) or editing for system-wide changes. Example ~/.mostrc:

    % Color settings
    color normal lightgray black
    color status yellow blue
    color underline yellow black
    color overstrike brightblue black

    A list of all keybindings may be found at . To get a basic less/-like configuration, you can copy to ~/.mostrc. The lesskeys rc included with most does not include 'g' or 'G', so you will also have to add these lines to ~/.mostrc:

    setkey bob "g"
    setkey eob "G"
    setkey page_down "d"
    setkey page_up "u"

    You may also want to set the keybinding in the rc if you do not like the default of 'J'.

    Another example showing keybindings similar to (jump to line is set to 'J'):

    % less-like keybindings
    unsetkey "^K"
    unsetkey "g"
    unsetkey "G"
    unsetkey ":"
    
    setkey next_file ":n"
    setkey find_file ":e"
    setkey next_file ":p"
    setkey toggle_options ":o"
    setkey toggle_case ":c"
    setkey delete_file ":d"
    setkey exit ":q"
    
    setkey bob "g"
    setkey eob "G"
    setkey down "e"
    setkey down "E"
    setkey down "j"
    setkey down "^N"
    setkey up "y"
    setkey up "^Y"
    setkey up "k"
    setkey up "^P"
    setkey up "^K"
    setkey page_down "f"
    setkey page_down "^F"
    setkey page_up "b"
    setkey page_up "^B"
    setkey other_window "z"
    setkey other_window "w"
    setkey search_backward "?"
    setkey bob "p"
    setkey goto_mark "'"
    setkey find_file "E"
    setkey edit "v"

    Using X resources

    A quick way to add color to manual pages viewed on /uxterm or is to modify .

    xterm
    *VT100.colorBDMode:     true
    *VT100.colorBD:         red
    *VT100.colorULMode:     true
    *VT100.colorUL:         cyan

    which replaces the decorations with the colors. Also add:

    *VT100.veryBoldColors: 6

    if you want colors and decorations (bold or underline) at the same time. See for more information.

    rxvt-unicode
    URxvt.colorIT:      #87af5f
    URxvt.colorBD:      #d7d7d7
    URxvt.colorUL:      #87afd7

    Run:

    $ xrdb -load ~/.Xresources

    Launch a new or and you should see colorful man pages.

    This combination puts colors to bold and underlined words in or to bold, underlined, and italicized text in . You can play with different combinations of these attributes. See the sources (archived) of this item.

    pacman

    Pacman has a color option. Uncomment the line in .

    Wrappers

    Universal wrappers

    (most of them outdated, but still functioning)

    They go with multiple preconfigured presets that can be changed, and new ones can be created/contributed.

    • rainbow Colorize commands output or STDIN using patterns.
      Presets: df, diff, env, host, ifconfig, java-stack-trace, jboss, jonas, md5sum, mvn2, mvn3, ping, tomcat, top, traceroute.
    https://github.com/nicoulaj/rainbow || rainbowAUR

    Libraries for colorizing an output

    • lolcat Ruby program that makes the output colorful like a rainbow
    https://github.com/busyloop/lolcat/ || lolcat

    Compilers

      diff

      Diff has built-in color output, which is reasonable to use. But the following wrappers can be used:

      • cwdiff (w)diff wrapper with directories support and highlighting.
      https://github.com/junghans/cwdiff || cwdiffAUR

        cat

          source-highlight

          You can enable code syntax coloring in less. First, install , then add these lines to your shell configuration file:

          lesspipe

          Frequent users of the command line interface might want to install .

          Users may now list the compressed files inside of an archive using their pager:

          lesspipe also grants less the ability of interfacing with files other than archives, serving as an alternative for the specific command associated for that file-type (such as viewing HTML via python-html2text).

          Re-login after installing lesspipe in order to activate it, or source .

          Make

            Ping

              Shells

              bash

              See Bash/Prompt customization#Colors.

              Fish

              See Fish#Web interface.

              xonsh

              See Customizing the Prompt.

              zsh

              See Zsh#Colors.

              Terminal emulators

              Virtual console

              The colors in the Linux virtual console running on the framebuffer can be changed. This is done by writing the escape code , where is the hexadecimal index of the color from 0-F, and is a traditional hexadecimal RGB code.

              For example, to reuse existing colors defined in , add the following to the shell initialization file (such as ):

              if [ "$TERM" = "linux" ]; then
                  _SEDCMD='s/.*\*color\([0-9]\{1,\}\).*#\([0-9a-fA-F]\{6\}\).*/\1 \2/p'
                  for i in $(sed -n "$_SEDCMD" $HOME/.Xresources | awk '$1 < 16 {printf "\\e]P%X%s", $1, $2}'); do
                      echo -en "$i"
                  done
                  clear
              fi

              Login screen

              The below is a colored example of the virtual console login screen in . Create a backup of the original file with mv /etc/issue /etc/issue.bak as root, and create a new :

              \e[H\e[2J
                                                                           \e[1;30m| \e[34m\r \s
                    \e[36;1m/\\\\                        \e[37m||      \e[36m| =                 \e[30m|
                   \e[36m/  \\\\                       \e[37m||      \e[36m|                   \e[30m| \e[32m\t
                  \e[1;36m/ \e[0;36m.. \e[1m\\\\   \e[37m//==\\\\\\ ||/= /==\\\\ ||/=\\\\  \e[36m| | |/\\\\ |  | \\\\ /  \e[30m| \e[32m\d
                 \e[0;36m/ .  . \\\\ \e[37m||    || ||  ||     ||  ||  \e[36m| | |  | |  |   X   \e[1;30m|
                \e[0;36m/  .  .  \\\\ \e[37m\\\\\\==/| ||   \\\\==/ ||  ||  \e[36m| | |  |\  \\/|  / \\\\ \e[1;30m| \e[31m\U
               \e[0;36m/ ..    .. \\\\   \e[0;37mA simple, lightweight linux distribution.   \e[1;30m|
              \e[0;36m/_'        `_\\\\                                              \e[1;30m| \e[35m\l \e[0mon \e[1;33m\n
              \e[0m 

              See also:

              X window system

              Most Xorg terminals, including xterm and urxvt, support at least 16 basic colors. The colors 0-7 are the 'normal' colors. Colors 8-15 are their 'bright' counterparts, used for highlighting. These colors can be modified through X resources, or through specific terminal settings. For example:

              See also:

              Display the 256 colors

              Prints the 256 colors across the screen.

              $ (x=`tput op` y=`printf %76s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done)

              Display tput escape codes

              Replace tput op with whatever tput you want to trace. is the default foreground and background color.

              Enumerate supported colors

              The following command will let you discover all the terminals you have terminfo support for, and the number of colors each terminal supports. The possible values are: 8, 15, 16, 52, 64, 88 and 256.

              $ for T in `find /usr/share/terminfo -type f -printf '%f '`;do echo "$T `tput -T $T colors`";done|sort -nk2
              Eterm-88color 88
              rxvt-88color 88
              xterm+88color 88
              xterm-88color 88
              Eterm-256color 256
              gnome-256color 256
              konsole-256color 256
              putty-256color 256
              rxvt-256color 256
              screen-256color 256
              screen-256color-bce 256
              screen-256color-bce-s 256
              screen-256color-s 256
              xterm+256color 256
              xterm-256color 256
              

              Enumerate terminal capabilities

              This command is useful to see what features that are supported by your terminal.

              Color scheme scripts

              See for scripts which display a chart of your current terminal scheme.

              True color support

              Some terminals support the full range of 16 million colors (RGB, each with 8 bit resolution): xterm, konsole, st, etc. The corresponding TERM values , , , etc. are supported starting with ncurses version 6.1 . For more info about terminal emulators and applications that support true color, see .

              Note that the Linux kernel supports the SGR escape sequences for true-color, but it is pointless to use it, because the driver maps the 24-bit color specifications to a 256-colors color map in the kernel (see the functions , ). For this reason, there is no terminfo entry linux-direct.

              gollark: Approval voting's neat too.
              gollark: I guess it *could* work for non-presidential voting things, but I don't actually know how those work in the US.
              gollark: > If percentages of Independent votes were to increase as a trend over time then there could be a possibility of more representative pluralismNo, the electoral college system essentially forbids this.
              gollark: In a two-party system, voting conveys one bit of legally binding information. This is not very much.
              gollark: Also, your definition of fascism seems... excessively wide, mautam.

              See also

              This article is issued from Archlinux. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.