为文本着色

Cha*_*lie 5 bash

如何使用 Bash 显示彩色文本?

  • a:棕色背景上的白色文本
  • b:黄底黑字

echo -e "bbb aaa bbb"
Run Code Online (Sandbox Code Playgroud)

echo -e "aaa bbb aaa"
Run Code Online (Sandbox Code Playgroud)

我的结果不太好:-(

b3h*_*0th 6

# text
black='\e[0;30m'
white='\e[0;37m'
yellow='\e[0;33m'

# background
white_bg='\e[47m'

echo -e "${black}black test"
echo -e "${white_bg}white bg and black test"
echo -e "${yellow}yellow test"
Run Code Online (Sandbox Code Playgroud)

  • 不要对终端转义进行硬编码 - 使用 `tput` 来代替,以获得实际使用的终端的正确值(如果有)。 (2认同)

jen*_*-na 5

您可以在您的~/.bashrc

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
Run Code Online (Sandbox Code Playgroud)

之后您可以使用echo

echo -e "${txtred}asd${txtwht}"
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到更多颜色。


npo*_*cop 5

以下是使用 tput 的方法:

txtblk=$(tput setaf 0) # Black - Regular
txtred=$(tput setaf 1) # Red
txtgrn=$(tput setaf 2) # Green
txtylw=$(tput setaf 3) # Yellow
txtblu=$(tput setaf 4) # Blue
txtpur=$(tput setaf 5) # Purple
txtcyn=$(tput setaf 6) # Cyan
txtwht=$(tput setaf 7) # White
Run Code Online (Sandbox Code Playgroud)

但保存它的方法并.bashrc不可取,因为每当失败时禁用颜色是一个很好的做法-t test

因此,更好的方法是创建一个包含以下内容的文件:

[[ -t 1 ]] || export TERM=dumb
txtblk=$(tput setaf 0) # Black - Regular
txtred=$(tput setaf 1) # Red
txtgrn=$(tput setaf 2) # Green
txtylw=$(tput setaf 3) # Yellow
txtblu=$(tput setaf 4) # Blue
txtpur=$(tput setaf 5) # Purple
txtcyn=$(tput setaf 6) # Cyan
txtwht=$(tput setaf 7) # White
Run Code Online (Sandbox Code Playgroud)

并在您需要颜色时获取它。tput当标准输出不是终端时,将在哑终端上放置零长度字符串。所以:

./my-script会打印颜色,但./my-script | grep foo不会将颜色代码发送到grep.

编辑:颜色已被修复以表示颜色的典型编号,按照https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit

请注意,可以更改特定终端的颜色顺序,但这也是不明智的。