在終端輸出彩色

出自 Arch Linux 中文维基

本文內容或本節內容已經過期。

原因: 請提供模板的第一個位置參數以概括原因。 (在Talk:在終端輸出彩色討論)

本文或本節需要翻譯。要貢獻翻譯,請訪問簡體中文翻譯團隊

附註: Not translated yet.(在 Talk:在終端輸出彩色# 中討論)

diff[編輯 | 編輯原始碼]

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

$ alias diff 'diff --color=auto'

Alternatively, the following wrappers can be used:

  • colordiff — A Perl script wrapper for 'diff' that produces the same output but with pretty 'syntax' highlighting
https://www.colordiff.org/ || colordiff
  • cwdiff — A (w)diff wrapper to support directories and colorize the output
https://github.com/junghans/cwdiff || cwdiffAUR, cwdiff-gitAUR

grep[編輯 | 編輯原始碼]

除了美觀用途以外,grep的彩色化輸出也對學習regexpgrep功能很有用。

請在您的shell配置文件添加以下內容以啟用默認的彩色化輸出,適用於Bash

~/.bashrc
alias grep='grep --color=auto'

如果要顯示行數,添加"-n"參數即可.

您還可以直接設置GREP_OPTIONS 環境變量,不過這有可能會影響到那些用到grep [1]的腳本:

 export GREP_COLOR="1;32"

GREP_COLORS環境變量其實可以定義特定的搜索。

less[編輯 | 編輯原始碼]

環境變量[編輯 | 編輯原始碼]

請在您的 shell 配置文件添加:

~/.bashrc
export LESS=-R
export LESS_TERMCAP_mb=$'\E[1;31m'
export LESS_TERMCAP_md=$'\E[1;36m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[1;32m'

值隨您所願修改,請參照:ANSI escape code

注意: The LESS_TERMCAL_xx variables is currently undocumented in less(1), for a detailed explanation on these sequences, see this answer.

Wrappers[編輯 | 編輯原始碼]

您可直接開啟less內置的代碼高亮。先安裝 軟件包 source-highlight,再在您的Shell配置文件裡添加以下:

~/.bashrc
export LESSOPEN="| /usr/bin/source-highlight-esc.sh %s"
export LESS='-R '

經常使用命令行界面的用户可以安裝lesspipe

用户可以使用以下 less 命令列出一個壓縮包裡的文件列表:

$ less compressed_file.tar.gz
==> use tar_file:contained_file to view a file in the archive
-rw------- username/group  695 2008-01-04 19:24 compressed_file/content1
-rw------- username/group   43 2007-11-07 11:17 compressed_file/content2
compressed_file.tar.gz (END)

lesspipe還被賦予less對文件而不僅是壓縮包進行交互的能力,從而成為打開某一種文件的一個新工具(比如用來代替python-html2text查看html文件。

安裝完lesspipe後需重新登錄以激活其功能,或者運行

source /etc/profile.d/lesspipe.sh

讀取標準輸入時彩色化輸出[編輯 | 編輯原始碼]

注意: 建議將這些 #環境變量 添加到 ~/.bashrc or ~/.zshrc. 因為本節完全基於: export LESS=R 寫成

當你運行一個命令和使用管道連接 標準輸出 (stdout) 到 less 作為分頁視圖 (e.g. yaourt -Qe --date | less), 你也許會發現輸出不再是彩色化的. 這通常是因為該程序試圖檢測如果其 stdout 是交互式終端, 在這種情況下將輸出彩色化文本,否則輸出未着色文本. 當你想重定向 stdout 到一個文件中,這是一個很好的行為, e.g. yaourt -Qe --date > pkglst-backup.txt. 但是,當你想在 less 瀏覽輸出時這將不是很好的行為.

一些程序提供禁用交互式 tty 檢測的選項:

# dmesg --color=always | less

如果程序不提供任何類似選項,可以欺騙程序相信stdout 是交互式終端,有幾種可行方式:

  • stdoutisatty 是一個用c寫成的小程序, 它可以調用 "fake interactive tty". 你可以通過 AUR: stdoutisattyAUR安裝. 用法示例:
$ stdoutisatty yaourt -Qe --date | less
  • unbuffer 是一個基於 shTcl 的很好的 (手冊比程序本身還要長), 古老的腳本. unbuffer 附帶 expect. 我們只需要這樣使用:
$ unbuffer yaourt -Qe --date | less

zptyzsh 的一個模塊, 這裏有一個來自 依雲[2] 的小函數, 將其放入 ~/.zshrc:

~/.zshrc
zmodload zsh/zpty

pty() {
	zpty pty-${UID} ${1+$@}
	if [[ ! -t 1 ]];then
		setopt local_traps
		trap '' INT
	fi
	zpty -r pty-${UID}
	zpty -d pty-${UID}
}

ptyless() {
	pty $@ | less
}

用法:

$ ptyless program

通過管道轉接到其它程序 (less in this example):

$ pty program | less

ls[編輯 | 編輯原始碼]

可以使用一個簡單的命令別名啟用彩色輸出功能,~/.bashrc文件應該已經有一句從/etc/skel/.bashrc複製過來的指定別名命令:

alias ls='ls --color=auto'

以下步驟可以進一步改進ls的彩色輸出功能,比如損壞的符號連結顯示為紅色,把以下內容添加到~/.bashrc,然後重新登錄,或者把腳本source一下:

eval $(dircolors -b)

man[編輯 | 編輯原始碼]

對很多人來説,彩色手冊頁比黑白的更加易於大腦消化吸收。

有兩種常用的實現man手冊頁彩色顯示的方法:使用 mostless .

使用 less[編輯 | 編輯原始碼]

You can set various LESS_TERMCAP_* environment variables to change how it highlights text. For example, LESS_TERMCAP_md is used for bold text and LESS_TERMCAP_me is used to reset to normal text formatting[3].

In Bash, the escape sequences you can use are the same ones from Bash/Prompt customization and these variables can be defined in a function wrapping the man command:

~/.bashrc
man() {
    LESS_TERMCAP_md=$'\e[01;31m' \
    LESS_TERMCAP_me=$'\e[0m' \
    LESS_TERMCAP_se=$'\e[0m' \
    LESS_TERMCAP_so=$'\e[01;44;33m' \
    LESS_TERMCAP_ue=$'\e[0m' \
    LESS_TERMCAP_us=$'\e[01;32m' \
    command man "$@"
}

For Fish you could accomplish this with:

~/.config/fish/config.fish
set -xU LESS_TERMCAP_md (printf "\e[01;31m")
set -xU LESS_TERMCAP_me (printf "\e[0m")
set -xU LESS_TERMCAP_se (printf "\e[0m")
set -xU LESS_TERMCAP_so (printf "\e[01;44;33m")
set -xU LESS_TERMCAP_ue (printf "\e[0m")
set -xU LESS_TERMCAP_us (printf "\e[01;32m")

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

For a detailed explanation on these variables, see this answer. Bash/Prompt customization#Examples has some (non-Bash-specific) examples of escape sequences that can be used.

Using most[編輯 | 編輯原始碼]

The basic function of 'most' is similar to less and more, 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.

pacman 安裝軟件包 most.

編輯文件/etc/man_db.conf,去掉pager項的註釋並修改為:

DEFINE     pager     most -s

然後測試一下:

$ man whatever_man_page

通過修改~/.mostrc(不存在的話請自行創建)或全局配置文件 /etc/most.conf。示例~/.mostrc:

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

以下示例配置使用類似less的快捷鍵:

% 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 xterm/uxterm or rxvt-unicode is to modify ~/.Xresources.

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 xterm(1) for a description of the veryBoldColors resource.

rxvt-unicode[編輯 | 編輯原始碼]

URxvt.colorIT:      #87af5f
URxvt.colorBD:      #d7d7d7
URxvt.colorUL:      #87afd7

Run:

$ xrdb -load ~/.Xresources

Launch a new xterm/uxterm or rxvt-unicode and you should see colorful man pages.

This combination puts colors to bold and underlined words in xterm/uxterm or to bold, underlined, and italicized text in rxvt-unicode. You can play with different combinations of these attributes (see the sources (archived) of this item).

pacman[編輯 | 編輯原始碼]

Pacman has a color option. Uncomment the Color line in /etc/pacman.conf.

Wrappers for other programs[編輯 | 編輯原始碼]

(most of them outdated but still functioning)

Universal wrappers with multiple preconfigured presets[編輯 | 編輯原始碼]

  • 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 || not packaged? search in AUR
  • grc — Yet another colouriser for beautifying your logfiles or output of commands.
    Presets: configure, cvs, df, diff, esperanto, gcc, irclog, ldap, log, mount, netstat, ping, proftpd, traceroute, wdiff.
https://github.com/pengwynn/grc || grc
  • colorlogs — Colorize commands output or STDIN using patterns.
    Presets: logs, git status, ant, maven.
https://github.com/memorius/colorlogs || not packaged? search in AUR
  • cope — A colourful wrapper for terminal programs.
    Presets: acpi, arp, cc, df, dprofpp, fdisk, free, g++, gcc, id, ifconfig, ls, lspci, lsusb, make, md5sum, mpc, netstat, nm, nmap, nocope, ping, pmap, ps, readelf, route, screen, sha1sum, sha224sum, sha256sum, sha384sum, sha512sum, shasum, socklist, stat, strace, tcpdump, tracepath, traceroute, w, wget, who, xrandr.
https://github.com/yogan/cope || cope-gitAUR
  • cw — A non-intrusive real-time ANSI color wrapper for common unix-based commands.
    Presets: arp, arping, auth.log@, blockdev, cal, cksum, clock, configure, cpuinfo@, crontab@, cw-pipe, cw-test.cgi, date, df, diff, dig, dmesg, du, env, figlet, file, find, finger, free, fstab@, fuser, g++, gcc, group@, groups, hdparm, hexdump, host, hosts@, id, ifconfig, inittab@, iptables, last, lastlog, lsattr, lsmod, lsof, ltrace-color, make, md5sum, meminfo@, messages@, mount, mpg123, netstat, nfsstat, nmap, nslookup, objdump, passwd@, ping, pmap, pmap_dump, praliases, profile@, protocols@, ps, pstree, quota, quotastats, resolv.conf@, route, routel, sdiff, services@, showmount, smbstatus, stat, strace-color, sysctl, syslog, tar, tcpdump, tracepath, traceroute, umount, uname, uptime, users, vmstat, w, wc, whereis, who, xferlog.
http://cwrapper.sourceforge.net/ || cwAUR

Compilers[編輯 | 編輯原始碼]

  • colorgcc — A Perl wrapper to colorize the output of compilers with warning/error messages matching the gcc output format
https://schlueters.de/colorgcc.html || colorgcc

Ping[編輯 | 編輯原始碼]

  • prettyping — Add some great features to ping monitoring. A wrapper around the standard ping tool with the objective of making the output prettier, more colorful, more compact, and easier to read.
https://denilson.sa.nom.br/prettyping/ || prettyping

Make[編輯 | 編輯原始碼]

  • colormake — A simple wrapper around make to make it's output more readable.
http://bre.klaki.net/programs/colormake/ || colormakeAUR, colormake-gitAUR

Libraries[編輯 | 編輯原始碼]

  • ruby-rainbow — Rainbow is extension to ruby's String class adding support for colorizing text on ANSI terminal
https://rubygems.org/gems/rainbow/ || ruby-rainbow
  • python-blessings — A thin, practical wrapper around terminal coloring, styling, and positioning
https://pypi.python.org/pypi/blessings || python-blessings, python2-blessings[損壞的連結:package not found]

Shells[編輯 | 編輯原始碼]

bash[編輯 | 編輯原始碼]

See Bash/Prompt customization#Colors.

zsh[編輯 | 編輯原始碼]

See Zsh#Colors.

Fish[編輯 | 編輯原始碼]

See Fish#Web interface.

Terminal emulators[編輯 | 編輯原始碼]

Virtual console[編輯 | 編輯原始碼]

本文或本章節的語言、語法或風格需要改進。參考:Help:Style

原因:Lacks clarity on what "the colors" are, i.e. in #Virtual console they are about the representations of the 16 base colors (RGB values for yellow, red, blue, etc.), while in #Login screen they are about the base colors themselves. See also console_codes(4) and User:Isacdaavid/Linux_Console(在Talk:在終端輸出彩色討論)

The colors in the Linux virtual console—see console(4)[失效連結 2017-09-06]—running on the framebuffer can be changed. This is done by writing the escape code \\e]PXRRGGBB, where X is the hexadecimal index of the color from 0-F, and RRGGBB is a traditional hexadecimal RGB code.

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

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 /etc/issue. Create a backup of the original file with mv /etc/issue /etc/issue.bak as root, and create a new /etc/issue:

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

Save the file and make it executable with chmod +x /etc/issue.

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:

~/.Xresources
! Black + DarkGrey
*color0:  #000000
*color8:  #555753
! DarkRed + Red
*color1:  #ff6565
*color9:  #ff8d8d
! DarkGreen + Green
*color2:  #93d44f
*color10: #c8e7a8
! DarkYellow + Yellow
*color3:  #eab93d
*color11: #ffc123
! DarkBlue + Blue
*color4:  #204a87
*color12: #3465a4
! DarkMagenta + Magenta
*color5:  #ce5c00
*color13: #f57900
!DarkCyan + Cyan (both not tango)
*color6:  #89b6e2
*color14: #46a4ff
! LightGrey + White
*color7:  #cccccc
*color15: #ffffff
警吿: Color resources such as foreground and background can be read by other applications (such as emacs). This can be avoided by specifiying the class name, for example XTerm.foreground.

See also:

Display all 256 colors[編輯 | 編輯原始碼]

Prints all 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[編輯 | 編輯原始碼]

本文或本章節可能需要合併到Bash/Prompt_customization

附註: More context on tput is provided in that article(在 Talk:在終端輸出彩色 中討論)

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

$ ( strace -s5000 -e write tput op 2>&2 2>&1 ) | tee -a /dev/stderr | grep -o '"[^"]*"'
033[\033[1;34m"\33[39;49m"\033[00m

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[編輯 | 編輯原始碼]

本文或本章節可能需要合併到Bash/Prompt_customization

附註: More context on tput is provided in that article(在 Talk:在終端輸出彩色 中討論)

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

$ infocmp -1 | sed -nu 's/^[ \000\t]*//;s/[ \000\t]*$//;/[^ \t\000]\{1,\}/!d;/acsc/d;s/=.*,//p'|column -c80
bel	cuu	ich	kb2	kf15	kf3	kf44	kf59	mc0	rmso	smul
blink	cuu1	il	kbs	kf16	kf30	kf45	kf6	mc4	rmul	tbc
bold	cvvis	il1	kcbt	kf17	kf31	kf46	kf60	mc5	rs1	u6
cbt	dch	ind	kcub1	kf18	kf32	kf47	kf61	meml	rs2	u7
civis	dch1	indn	kcud1	kf19	kf33	kf48	kf62	memu	sc	u8
clear	dl	initc	kcuf1	kf2	kf34	kf49	kf63	op	setab	u9
cnorm	dl1	invis	kcuu1	kf20	kf35	kf5	kf7	rc	setaf	vpa

Color scheme scripts[編輯 | 編輯原始碼]

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

See also[編輯 | 編輯原始碼]