shell 脚本中的“友好”终端颜色名称?

the*_*ror 27 colors bash terminal shell-script

我知道 Ruby 和 Javascript 等语言中的库可以通过使用“红色”等颜色名称来更轻松地为终端脚本着色。

但是对于 Bash 或 Ksh 或其他任何东西中的 shell 脚本,是否有类似的东西?

jas*_*yan 43

您可以在 bash 脚本中定义颜色,如下所示:

red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'
Run Code Online (Sandbox Code Playgroud)

然后使用它们以您需要的颜色打印:

printf "%s\n" "Text in ${red}red${end}, white and ${blu}blue${end}."
Run Code Online (Sandbox Code Playgroud)


Rah*_*til 12

您可以使用tputprintf

使用tput,

只需创建如下功能并使用它们

shw_grey () {
    echo $(tput bold)$(tput setaf 0) $@ $(tput sgr 0)
}

shw_norm () {
    echo $(tput bold)$(tput setaf 9) $@ $(tput sgr 0)
}

shw_info () {
    echo $(tput bold)$(tput setaf 4) $@ $(tput sgr 0)
}

shw_warn () {
    echo $(tput bold)$(tput setaf 2) $@ $(tput sgr 0)
}
shw_err ()  {
    echo $(tput bold)$(tput setaf 1) $@ $(tput sgr 0)
}
Run Code Online (Sandbox Code Playgroud)

你可以使用上面的函数调用 shw_err "WARNING:: Error bla bla"

使用 printf

print red; echo -e "\e[31mfoo\e[m"
Run Code Online (Sandbox Code Playgroud)

  • `echo -e` 不是 `printf`,还需要警告它与 `tput` 选项的不同之处在于它不会自动适应 `$TERM`。 (2认同)

Gil*_*il' 8

在 zsh 中

autoload -U colors
colors

echo $fg[green]YES$fg[default] or $fg[red]NO$fg[default]?
Run Code Online (Sandbox Code Playgroud)


Wil*_*ard 5

对于简单的常见用途(只有单一颜色的全行文本,带有尾随换行符),我修改了jasonwryan 的代码,如下所示:

#!/bin/bash

red='\e[1;31m%s\e[0m\n'
green='\e[1;32m%s\e[0m\n'
yellow='\e[1;33m%s\e[0m\n'
blue='\e[1;34m%s\e[0m\n'
magenta='\e[1;35m%s\e[0m\n'
cyan='\e[1;36m%s\e[0m\n'

printf "$green"   "This is a test in green"
printf "$red"     "This is a test in red"
printf "$yellow"  "This is a test in yellow"
printf "$blue"    "This is a test in blue"
printf "$magenta" "This is a test in magenta"
printf "$cyan"    "This is a test in cyan"
Run Code Online (Sandbox Code Playgroud)