我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。 我怎样才能做到这一点?
#1楼
您可以使用很棒的tput
命令(在Ignacio的答案中建议)来为各种事物产生终端控制代码。
用法
稍后将讨论特定的tput
子命令。
直接
调用tput
作为命令序列的一部分:
tput setaf 1; echo "this is red text"
使用;
而不是&&
因此如果tput
错误仍然显示文本。
外壳变量
另一种选择是使用外壳变量:
red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
echo "${red}red text ${green}green text${reset}"
tput
产生的字符序列被终端解释为具有特殊含义。 他们不会自己显示。 请注意,它们仍然可以保存到文件中,也可以由终端以外的程序作为输入进行处理。
命令替换
使用命令替换将tput
的输出直接插入echo
字符串中可能会更方便:
echo "$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)"
例
上面的命令在Ubuntu上生成:
前景和背景颜色命令
tput setab [1-7] # Set the background colour using ANSI escape
tput setaf [1-7] # Set the foreground colour using ANSI escape
颜色如下:
Num Colour #define R G B
0 black COLOR_BLACK 0,0,0
1 red COLOR_RED 1,0,0
2 green COLOR_GREEN 0,1,0
3 yellow COLOR_YELLOW 1,1,0
4 blue COLOR_BLUE 0,0,1
5 magenta COLOR_MAGENTA 1,0,1
6 cyan COLOR_CYAN 0,1,1
7 white COLOR_WHITE 1,1,1
还有颜色设置功能的非ANSI版本( setb
代替setab
, setf
代替setaf
),它们使用不同的数字,此处未给出。
文字模式命令
tput bold # Select bold mode
tput dim # Select dim (half-bright) mode
tput smul # Enable underline mode
tput rmul # Disable underline mode
tput rev # Turn on reverse video mode
tput smso # Enter standout (bold) mode
tput rmso # Exit standout mode
光标移动命令
tput cup Y X # Move cursor to screen postion X,Y (top left is 0,0)
tput cuf N # Move N characters forward (right)
tput cub N # Move N characters back (left)
tput cuu N # Move N lines up
tput ll # Move to last line, first column (if no cup)
tput sc # Save the cursor position
tput rc # Restore the cursor position
tput lines # Output the number of lines of the terminal
tput cols # Output the number of columns of the terminal
清除并插入命令
tput ech N # Erase N characters
tput clear # Clear screen and move the cursor to 0,0
tput el 1 # Clear to beginning of line
tput el # Clear to end of line
tput ed # Clear to end of screen
tput ich N # Insert N characters (moves rest of line forward!)
tput il N # Insert N lines
其他命令
tput sgr0 # Reset text format to the terminal's default
tput bel # Play a bell
使用compiz摆动窗口时 , bel
命令会使终端摆动一秒钟,以引起用户的注意。
剧本
tput
接受每行包含一个命令的脚本,这些脚本按顺序在tput
退出之前执行。
通过回显多行字符串并将其用管道传递来避免使用临时文件:
echo -e "setf 7\nsetb 1" | tput -S # set fg white and bg red
也可以看看
- 见
man 1 tput
- 有关完整的命令列表和这些选项的更多详细信息,请参见
man 5 terminfo
。 (相应的tput
命令在Cap-name
81行开始的巨大表的Cap-name
列中列出。)
#2楼
一种仅对一个echo
更改颜色的巧妙方法是定义以下功能:
function coloredEcho(){
local exp=$1;
local color=$2;
if ! [[ $color =~ '^[0-9]$' ]] ; then
case $(echo $color | tr '[:upper:]' '[:lower:]') in
black) color=0 ;;
red) color=1 ;;
green) color=2 ;;
yellow) color=3 ;;
blue) color=4 ;;
magenta) color=5 ;;
cyan) color=6 ;;
white|*) color=7 ;; # white or invalid color
esac
fi
tput setaf $color;
echo $exp;
tput sgr0;
}
用法:
coloredEcho "This text is green" green
或者,您可以直接使用Drew的答案中提到的颜色代码:
coloredEcho "This text is green" 2
#3楼
red='\e[0;31m'
NC='\e[0m' # No Color
echo -e "${red}Hello Stackoverflow${NC}"
这个答案是正确的,除了对颜色的调用不应放在引号内。
echo -e ${red}"Hello Stackoverflow"${NC}
应该做到的。
#4楼
为了提高可读性
如果要提高代码的可读性 ,可以先echo
显字符串,然后再使用sed
添加颜色:
echo 'Hello World!' | sed $'s/World/\e[1m&\e[0m/'
#5楼
这些代码可在我的Ubuntu机器上使用:
echo -e "\x1B[31m foobar \x1B[0m"
echo -e "\x1B[32m foobar \x1B[0m"
echo -e "\x1B[96m foobar \x1B[0m"
echo -e "\x1B[01;96m foobar \x1B[0m"
echo -e "\x1B[01;95m foobar \x1B[0m"
echo -e "\x1B[01;94m foobar \x1B[0m"
echo -e "\x1B[01;93m foobar \x1B[0m"
echo -e "\x1B[01;91m foobar \x1B[0m"
echo -e "\x1B[01;90m foobar \x1B[0m"
echo -e "\x1B[01;89m foobar \x1B[0m"
echo -e "\x1B[01;36m foobar \x1B[0m"
这会以不同的颜色打印字母abcd:
echo -e "\x1B[0;93m a \x1B[0m b \x1B[0;92m c \x1B[0;93m d \x1B[0;94m"
对于循环:
for (( i = 0; i < 17; i++ ));
do echo "$(tput setaf $i)This is ($i) $(tput sgr0)";
done
#6楼
这是颜色开关 \\033[
。 查看历史 。
颜色代码例如1;32
(浅绿色), 0;34
(蓝色), 1;34
(浅蓝色)等。
我们用彩色开关终止颜色序列\\033[
和0m
, 无 -color代码。 就像以标记语言打开和关闭选项卡一样。
SWITCH="\033["
NORMAL="${SWITCH}0m"
YELLOW="${SWITCH}1;33m"
echo "${YELLOW}hello, yellow${NORMAL}"
简单的颜色echo
功能解决方案:
cecho() {
local code="\033["
case "$1" in
black | bk) color="${code}0;30m";;
red | r) color="${code}1;31m";;
green | g) color="${code}1;32m";;
yellow | y) color="${code}1;33m";;
blue | b) color="${code}1;34m";;
purple | p) color="${code}1;35m";;
cyan | c) color="${code}1;36m";;
gray | gr) color="${code}0;37m";;
*) local text="$1"
esac
[ -z "$text" ] && local text="$color$2${code}0m"
echo "$text"
}
cecho "Normal"
cecho y "Yellow!"
#7楼
您可以使用一些变量:
# Reset
Color_Off='\033[0m' # Text Reset
# Regular Colors
Black='\033[0;30m' # Black
Red='\033[0;31m' # Red
Green='\033[0;32m' # Green
Yellow='\033[0;33m' # Yellow
Blue='\033[0;34m' # Blue
Purple='\033[0;35m' # Purple
Cyan='\033[0;36m' # Cyan
White='\033[0;37m' # White
# Bold
BBlack='\033[1;30m' # Black
BRed='\033[1;31m' # Red
BGreen='\033[1;32m' # Green
BYellow='\033[1;33m' # Yellow
BBlue='\033[1;34m' # Blue
BPurple='\033[1;35m' # Purple
BCyan='\033[1;36m' # Cyan
BWhite='\033[1;37m' # White
# Underline
UBlack='\033[4;30m' # Black
URed='\033[4;31m' # Red
UGreen='\033[4;32m' # Green
UYellow='\033[4;33m' # Yellow
UBlue='\033[4;34m' # Blue
UPurple='\033[4;35m' # Purple
UCyan='\033[4;36m' # Cyan
UWhite='\033[4;37m' # White
# Background
On_Black='\033[40m' # Black
On_Red='\033[41m' # Red
On_Green='\033[42m' # Green
On_Yellow='\033[43m' # Yellow
On_Blue='\033[44m' # Blue
On_Purple='\033[45m' # Purple
On_Cyan='\033[46m' # Cyan
On_White='\033[47m' # White
# High Intensity
IBlack='\033[0;90m' # Black
IRed='\033[0;91m' # Red
IGreen='\033[0;92m' # Green
IYellow='\033[0;93m' # Yellow
IBlue='\033[0;94m' # Blue
IPurple='\033[0;95m' # Purple
ICyan='\033[0;96m' # Cyan
IWhite='\033[0;97m' # White
# Bold High Intensity
BIBlack='\033[1;90m' # Black
BIRed='\033[1;91m' # Red
BIGreen='\033[1;92m' # Green
BIYellow='\033[1;93m' # Yellow
BIBlue='\033[1;94m' # Blue
BIPurple='\033[1;95m' # Purple
BICyan='\033[1;96m' # Cyan
BIWhite='\033[1;97m' # White
# High Intensity backgrounds
On_IBlack='\033[0;100m' # Black
On_IRed='\033[0;101m' # Red
On_IGreen='\033[0;102m' # Green
On_IYellow='\033[0;103m' # Yellow
On_IBlue='\033[0;104m' # Blue
On_IPurple='\033[0;105m' # Purple
On_ICyan='\033[0;106m' # Cyan
On_IWhite='\033[0;107m' # White
bash , hex和octal的转义字符分别为:
| | bash | hex | octal | NOTE |
|-------+-------+--------+---------+------------------------------|
| start | \e | \x1b | \033 | |
| start | \E | \x1B | - | x cannot be capital |
| end | \e[0m | \x1m0m | \033[0m | |
| end | \e[m | \x1b[m | \033[m | 0 is appended if you omit it |
| | | | | |
简短的例子:
| color | bash | hex | octal | NOTE |
|-------------+--------------+----------------+----------------+---------------------------------------|
| start green | \e[32m<text> | \x1b[32m<text> | \033[32m<text> | m is NOT optional |
| reset | <text>\e[0m | <text>\1xb[0m | <text>\033[om | o is optional (do it as best practice |
| | | | | |
bash例外:
如果您打算在特殊的bash变量中使用这些代码
- PS0
- PS1
- PS2(=用于提示)
- PS4
您应该添加额外的转义字符,以便bash可以正确解释它们。 如果没有添加额外的转义字符,它就可以工作,但是当您使用Ctrl + r
在历史记录中进行搜索时,您将遇到问题。
bash例外规则
您应该在任何开始的ANSI代码之前添加\\[
,在任何结束的ANSI代码之后添加\\]
。
例:
正常使用: \\033[32mThis is in green\\033[0m
对于PS0 / 1/2/4: \\[\\033[32m\\]This is in green\\[\\033[m\\]
\\[
用于表示一系列不可打印的字符 \\]
用于不可打印字符序列的结尾
提示:要记住,您可以先添加\\[\\]
,然后将ANSI代码放在它们之间:
- \\[start-ANSI-code\\]
- \\[end-ANSI-code\\]
颜色序列的类型:
- 3/4位
- 8位
- 24位
在深入研究这些颜色之前,您应该了解以下代码的4种模式:
1.颜色模式
它修改了非文本颜色的样式。 例如,使颜色变亮或变暗。
-
0
重置 -
1;
比正常轻 -
2;
比正常暗
此模式不受广泛支持。 它完全支持Gnome终端。
2.文字模式
此模式用于修改文本的样式,而不是颜色。
-
3;
斜体 -
4;
强调 -
5;
闪烁(慢) -
6;
闪烁(快速) -
7;
相反 -
8;
隐藏 -
9;
划掉
并且几乎得到支持。
例如,KDE-Konsole支持5;
但是Gnome终端不支持,而Gnome支持8;
但是KDE不会。
3.前台模式
此模式用于给前景着色。
4.后台模式
此模式用于给背景着色。
下表总结了ANSI-color的3/4位版本
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| color-mode | octal | hex | bash | description | example (= in octal) | NOTE |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 0 | \033[0m | \x1b[0m | \e[0m | reset any affect | echo -e "\033[0m" | 0m equals to m |
| 1 | \033[1m | | | light (= bright) | echo -e "\033[1m####\033[m" | - |
| 2 | \033[2m | | | dark (= fade) | echo -e "\033[2m####\033[m" | - |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| text-mode | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 3 | \033[3m | | | italic | echo -e "\033[3m####\033[m" | |
| 4 | \033[4m | | | underline | echo -e "\033[4m####\033[m" | |
| 5 | \033[5m | | | blink (slow) | echo -e "\033[3m####\033[m" | |
| 6 | \033[6m | | | blink (fast) | ? | not wildly support |
| 7 | \003[7m | | | reverse | echo -e "\033[7m####\033[m" | it affects the background/foreground |
| 8 | \033[8m | | | hide | echo -e "\033[8m####\033[m" | it affects the background/foreground |
| 9 | \033[9m | | | cross | echo -e "\033[9m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| foreground | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 30 | \033[30m | | | black | echo -e "\033[30m####\033[m" | |
| 31 | \033[31m | | | red | echo -e "\033[31m####\033[m" | |
| 32 | \033[32m | | | green | echo -e "\033[32m####\033[m" | |
| 33 | \033[32m | | | yellow | echo -e "\033[33m####\033[m" | |
| 34 | \033[32m | | | blue | echo -e "\033[34m####\033[m" | |
| 35 | \033[32m | | | purple | echo -e "\033[35m####\033[m" | real name: magenta = reddish-purple |
| 36 | \033[32m | | | cyan | echo -e "\033[36m####\033[m" | |
| 37 | \033[32m | | | white | echo -e "\033[37m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 38 | 8/24 | This is for special use of 8-bit or 24-bit |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| background | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 40 | \033[40m | | | black | echo -e "\033[40m####\033[m" | |
| 41 | \033[41m | | | red | echo -e "\033[41m####\033[m" | |
| 42 | \033[42m | | | green | echo -e "\033[42m####\033[m" | |
| 43 | \033[43m | | | yellow | echo -e "\033[43m####\033[m" | |
| 44 | \033[44m | | | blue | echo -e "\033[44m####\033[m" | |
| 45 | \033[45m | | | purple | echo -e "\033[45m####\033[m" | real name: magenta = reddish-purple |
| 46 | \033[46m | | | cyan | echo -e "\033[46m####\033[m" | |
| 47 | \033[47m | | | white | echo -e "\033[47m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 48 | 8/24 | This is for special use of 8-bit or 24-bit | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
下表总结了ANSI-color的8位版本
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| 0-7 | \033[38;5 | \x1b[38;5 | \e[38;5 | standard. normal | echo -e '\033[38;5;1m####\033[m' | |
| 8-15 | | | | standard. light | echo -e '\033[38;5;9m####\033[m' | |
| 16-231 | | | | more resolution | echo -e '\033[38;5;45m####\033[m' | has no specific pattern |
| 232-255 | | | | | echo -e '\033[38;5;242m####\033[m' | from black to white |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| 0-7 | | | | standard. normal | echo -e '\033[48;5;1m####\033[m' | |
| 8-15 | | | | standard. light | echo -e '\033[48;5;9m####\033[m' | |
| 16-231 | | | | more resolution | echo -e '\033[48;5;45m####\033[m' | |
| 232-255 | | | | | echo -e '\033[48;5;242m####\033[m' | from black to white |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
8位快速测试: for code in {0..255}; do echo -e "\\e[38;05;${code}m $code: Test"; done
下表总结了ANSI-color的24位版本
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | R = red | echo -e '\033[38;2;255;0;02m####\033[m' | R=255, G=0, B=0 |
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | G = green | echo -e '\033[38;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | B = blue | echo -e '\033[38;2;0;0;2552m####\033[m' | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| background | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | R = red | echo -e '\033[48;2;255;0;02m####\033[m' | R=255, G=0, B=0 |
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | G = green | echo -e '\033[48;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | B = blue | echo -e '\033[48;2;0;0;2552m####\033[m' | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
一些屏幕截图
.gif
前景8位摘要
.gif
背景8位摘要
颜色摘要及其值
在KDE终端上blinking
彩色模式拍摄
文字模式拍摄
合并还可以
更多的镜头
面向高级用户和程序员的提示和技巧:
我们可以在编程语言中使用这些代码吗?
是的你可以。 我对bash , c , c ++ , d perl , python有经验
它们会降低程序速度吗?
我觉得不行。
我们可以在Windows上使用它们吗?
3/4位是,如果您使用gcc
编译代码
Win-7上的一些屏幕截图
如何计算代码长度?
\\033[
= 2,其他部分1
我们在哪里可以使用这些代码?
任何有tty
解释器的地方 xterm
, gnome-terminal
, kde-terminal
, mysql-client-CLI
等。
例如,如果要使用mysql着色输出,可以使用Perl
#!/usr/bin/perl -n
print "\033[1m\033[31m$1\033[36m$2\033[32m$3\033[33m$4\033[m" while /([|+-]+)|([0-9]+)|([a-zA-Z_]+)|([^\w])/g;
将此代码存储在文件名: pcc
(= Perl Colorize Character)中,然后将文件a放入有效的PATH
然后在您喜欢的任何地方使用它。
ls | pcc
df | pcc
在mysql
内部,首先为pager
注册它,然后尝试:
[user2:db2] pager pcc
PAGER set to 'pcc'
[user2:db2] select * from table-name;
它不处理Unicode的。
这些代码仅进行着色吗?
不,他们可以做很多有趣的事情。 尝试:
echo -e '\033[2K' # clear the screen and do not move the position
要么:
echo -e '\033[2J\033[u' # clear the screen and reset the position
有很多初学者想用system( "clear" )
来清除屏幕,因此您可以使用它代替system(3)
调用
它们可以使用Unicode吗?
是。 \
这些颜色的哪个版本更好?
使用3/4-bit
很容易,但是使用24-bit
则非常准确和美观。
如果您没有使用html的经验,那么这里有一个快速教程:
24位表示: 00000000
和00000000
和00000000
。 每个8位用于特定颜色。 1..8
用于 和9..16
用于 和17..24
为
所以在html中 #FF0000
表示 这是: 255;0;0
在html #00FF00
表示 这是: 0;255;0
那有意义吗? 您想要什么颜色将其与这三个8位值组合在一起。
参考:
维基百科
ANSI转义序列
tldp.org
tldp.org
misc.flogisoft.com
我不记得的一些博客/网页
#8楼
这是我最近整理的一个简单小脚本,它将为任何管道输入着色,而不是使用“厕所”。
File: color.bsh
#!/usr/bin/env bash
## A.M.Danischewski 2015+(c) Free - for (all (uses and
## modifications)) - except you must keep this notice intact.
declare INPUT_TXT=""
declare ADD_LF="\n"
declare -i DONE=0
declare -r COLOR_NUMBER="${1:-247}"
declare -r ASCII_FG="\\033[38;05;"
declare -r COLOR_OUT="${ASCII_FG}${COLOR_NUMBER}m"
function show_colors() {
## perhaps will add bg 48 to first loop eventually
for fgbg in 38; do for color in {0..256} ; do
echo -en "\\033[${fgbg};5;${color}m ${color}\t\\033[0m";
(($((${color}+1))%10==0)) && echo; done; echo; done
}
if [[ ! $# -eq 1 || ${1} =~ ^-. ]]; then
show_colors
echo " Usage: ${0##*/} <color fg>"
echo " E.g. echo \"Hello world!\" | figlet | ${0##*/} 54"
else
while IFS= read -r PIPED_INPUT || { DONE=1; ADD_LF=""; }; do
PIPED_INPUT=$(sed 's#\\#\\\\#g' <<< "${PIPED_INPUT}")
INPUT_TXT="${INPUT_TXT}${PIPED_INPUT}${ADD_LF}"
((${DONE})) && break;
done
echo -en "${COLOR_OUT}${INPUT_TXT}\\033[00m"
fi
然后将其命名为红色(196): $> echo "text you want colored red" | color.bsh 196
#9楼
就像有些东西一样,通过grep将其突出显示为红色(但只能是红色)。 您还可以使用命名管道,使您的字符串更接近行尾:
grep '.*' --color=always <(echo "foobar")
#10楼
为了扩展这个答案 ,我们懒惰的人:
function echocolor() { # $1 = string
COLOR='\033[1;33m'
NC='\033[0m'
printf "${COLOR}$1${NC}\n"
}
echo "This won't be colored"
echocolor "This will be colorful"
#11楼
到目前为止,我最喜欢的答案是coloredEcho。
只是要发布另一个选项,您可以查看这个小工具xcol
https://ownyourbits.com/2017/01/23/colorize-your-stdout-with-xcol/
您就像grep一样使用它,并且它将为每个参数为stdin着色不同的颜色,例如
sudo netstat -putan | xcol httpd sshd dnsmasq pulseaudio conky tor Telegram firefox "[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+" ":[[:digit:]]+" "tcp." "udp." LISTEN ESTABLISHED TIME_WAIT
请注意,它接受sed将接受的任何正则表达式。
该工具使用以下定义
#normal=$(tput sgr0) # normal text
normal=$'\e[0m' # (works better sometimes)
bold=$(tput bold) # make colors bold/bright
red="$bold$(tput setaf 1)" # bright red text
green=$(tput setaf 2) # dim green text
fawn=$(tput setaf 3); beige="$fawn" # dark yellow text
yellow="$bold$fawn" # bright yellow text
darkblue=$(tput setaf 4) # dim blue text
blue="$bold$darkblue" # bright blue text
purple=$(tput setaf 5); magenta="$purple" # magenta text
pink="$bold$purple" # bright magenta text
darkcyan=$(tput setaf 6) # dim cyan text
cyan="$bold$darkcyan" # bright cyan text
gray=$(tput setaf 7) # dim white text
darkgray="$bold"$(tput setaf 0) # bold black = dark gray text
white="$bold$gray" # bright white text
我像这样在脚本中使用这些变量
echo "${red}hello ${yellow}this is ${green}coloured${normal}"
#12楼
这就是我用来查看所有组合并确定哪个显示很酷的内容:
for (( i = 0; i < 8; i++ )); do
for (( j = 0; j < 8; j++ )); do
printf "$(tput setab $i)$(tput setaf $j)(b=$i, f=$j)$(tput sgr0)\n"
done
done
#13楼
我写了赃物来实现这一目标。
你可以做
pip install swag
现在,您可以通过以下方式将所有转义命令以txt文件的形式安装到给定的目的地:
swag install -d <colorsdir>
甚至更容易通过:
swag install
将颜色安装到~/.colors
。
您可以像这样使用它们:
echo $(cat ~/.colors/blue.txt) This will be blue
或这样,我发现实际上更有趣:
swag print -c red -t underline "I will turn red and be underlined"
检查出asciinema !
#14楼
使用tput
计算颜色代码。 避免使用ANSI转义码(例如\\E[31;1m
表示红色),因为它不那么可移植。 例如,OS X上的Bash不支持它。
BLACK=`tput setaf 0`
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 5`
CYAN=`tput setaf 6`
WHITE=`tput setaf 7`
BOLD=`tput bold`
RESET=`tput sgr0`
echo -e "hello ${RED}some red text${RESET} world"
#15楼
感谢@ k-five的答案
declare -A colors
#curl www.bunlongheng.com/code/colors.png
# Reset
colors[Color_Off]='\033[0m' # Text Reset
# Regular Colors
colors[Black]='\033[0;30m' # Black
colors[Red]='\033[0;31m' # Red
colors[Green]='\033[0;32m' # Green
colors[Yellow]='\033[0;33m' # Yellow
colors[Blue]='\033[0;34m' # Blue
colors[Purple]='\033[0;35m' # Purple
colors[Cyan]='\033[0;36m' # Cyan
colors[White]='\033[0;37m' # White
# Bold
colors[BBlack]='\033[1;30m' # Black
colors[BRed]='\033[1;31m' # Red
colors[BGreen]='\033[1;32m' # Green
colors[BYellow]='\033[1;33m' # Yellow
colors[BBlue]='\033[1;34m' # Blue
colors[BPurple]='\033[1;35m' # Purple
colors[BCyan]='\033[1;36m' # Cyan
colors[BWhite]='\033[1;37m' # White
# Underline
colors[UBlack]='\033[4;30m' # Black
colors[URed]='\033[4;31m' # Red
colors[UGreen]='\033[4;32m' # Green
colors[UYellow]='\033[4;33m' # Yellow
colors[UBlue]='\033[4;34m' # Blue
colors[UPurple]='\033[4;35m' # Purple
colors[UCyan]='\033[4;36m' # Cyan
colors[UWhite]='\033[4;37m' # White
# Background
colors[On_Black]='\033[40m' # Black
colors[On_Red]='\033[41m' # Red
colors[On_Green]='\033[42m' # Green
colors[On_Yellow]='\033[43m' # Yellow
colors[On_Blue]='\033[44m' # Blue
colors[On_Purple]='\033[45m' # Purple
colors[On_Cyan]='\033[46m' # Cyan
colors[On_White]='\033[47m' # White
# High Intensity
colors[IBlack]='\033[0;90m' # Black
colors[IRed]='\033[0;91m' # Red
colors[IGreen]='\033[0;92m' # Green
colors[IYellow]='\033[0;93m' # Yellow
colors[IBlue]='\033[0;94m' # Blue
colors[IPurple]='\033[0;95m' # Purple
colors[ICyan]='\033[0;96m' # Cyan
colors[IWhite]='\033[0;97m' # White
# Bold High Intensity
colors[BIBlack]='\033[1;90m' # Black
colors[BIRed]='\033[1;91m' # Red
colors[BIGreen]='\033[1;92m' # Green
colors[BIYellow]='\033[1;93m' # Yellow
colors[BIBlue]='\033[1;94m' # Blue
colors[BIPurple]='\033[1;95m' # Purple
colors[BICyan]='\033[1;96m' # Cyan
colors[BIWhite]='\033[1;97m' # White
# High Intensity backgrounds
colors[On_IBlack]='\033[0;100m' # Black
colors[On_IRed]='\033[0;101m' # Red
colors[On_IGreen]='\033[0;102m' # Green
colors[On_IYellow]='\033[0;103m' # Yellow
colors[On_IBlue]='\033[0;104m' # Blue
colors[On_IPurple]='\033[0;105m' # Purple
colors[On_ICyan]='\033[0;106m' # Cyan
colors[On_IWhite]='\033[0;107m' # White
color=${colors[$input_color]}
white=${colors[White]}
# echo $white
for i in "${!colors[@]}"
do
echo -e "$i = ${colors[$i]}I love you$white"
done
结果
希望这张图片能帮助您为bash选择颜色:D
#16楼
这个问题已经被一遍又一遍地回答:-),但是为什么不呢。
第一次使用tput
在现代环境中比通过echo -E
手动注入ASCII代码更容易携带
这是一个快速的bash函数:
say() {
echo "$@" | sed \
-e "s/\(\(@\(red\|green\|yellow\|blue\|magenta\|cyan\|white\|reset\|b\|u\)\)\+\)[[]\{2\}\(.*\)[]]\{2\}/\1\4@reset/g" \
-e "s/@red/$(tput setaf 1)/g" \
-e "s/@green/$(tput setaf 2)/g" \
-e "s/@yellow/$(tput setaf 3)/g" \
-e "s/@blue/$(tput setaf 4)/g" \
-e "s/@magenta/$(tput setaf 5)/g" \
-e "s/@cyan/$(tput setaf 6)/g" \
-e "s/@white/$(tput setaf 7)/g" \
-e "s/@reset/$(tput sgr0)/g" \
-e "s/@b/$(tput bold)/g" \
-e "s/@u/$(tput sgr 0 1)/g"
}
现在您可以使用:
say @b@green[[Success]]
要得到:
关于tput
可移植性的注意事项
1986年9月首次上载tput(1)
源代码
tput(1)
在1990年代的X / Open curses语义中可用(1997标准具有以下提及的语义)。
因此,它是( 相当 )普遍。
#17楼
我们可以为文本和背景使用24位RGB真彩色 !
ESC[38;2;⟨r⟩;⟨g⟩;⟨b⟩m /*Foreground color*/
ESC[48;2;⟨r⟩;⟨g⟩;⟨b⟩m /*Background color*/
红色文字示例和结束标记:
echo -e "\e[38;2;255;0;0mHello world\e[0m"
发电机:
text.addEventListener("input",update) back.addEventListener("input",update) function update(){ let a = text.value.substr(1).match(/.{1,2}/g) let b = back.value.substr(1).match(/.{1,2}/g) out1.textContent = "echo -e \\"\\\\" + `033[38;2;${parseInt(a[0],16)};${parseInt(a[1],16)};${parseInt(a[2],16)}mHello\\"` out2.textContent = "echo -e \\"\\\\" + `033[48;2;${parseInt(b[0],16)};${parseInt(b[1],16)};${parseInt(b[2],16)}mWorld!\\"` }
div {padding:1rem;font-size:larger}
TEXT COLOR: <input type="color" id="text" value="#23233"> <br><div id="out1"></div> BACK COLOR: <input type="color" id="back" value="#FFFF00"> <br><div id="out2">
24位:具有16至24位颜色的“真彩色”图形卡变得很普遍,Xterm,KDE的Konsole以及所有基于libvte的终端(包括GNOME终端)都支持24位前景和背景颜色设置https:// /en.wikipedia.org/wiki/ANSI_escape_code#24位
在我的脚本中使用安全吗?
是! 8位和16位端子将仅作为可用调色板范围内的颜色显示为回退,以保持最佳的对比度,没有破损!
同样,没有人注意到ANSI代码7 反向视频的有用性。
通过交换前景色和背景色,它可以在任何终端方案颜色,黑色或白色背景或其他奇特的调色板上保持可读性。
例如,对于可在任何地方使用的红色背景:
echo -e "\033[31;7mHello world\e[0m";
这是更改终端内置方案时的外观:
这是用于gif的循环脚本。
for i in {30..49};do echo -e "\033[$i;7mReversed color code $i\e[0m Hello world!";done
参见https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters
#18楼
绝对应该在原始ANSI控制序列上使用tput。
因为存在大量不同的终端控制语言,所以系统通常具有中间通信层。 在数据库中查找当前检测到的终端类型的实际代码,然后向API发出标准请求,或者(从外壳程序)向命令发出标准请求。
这些命令之一是
tput
。tput
接受一组称为功能名称和任何参数(如果适用)的首字母缩写词,然后在terminfo数据库中为检测到的终端查找正确的转义序列,并输出正确的代码(终端希望能理解)。
来自http://wiki.bash-hackers.org/scripting/terminalcodes
就是说,我编写了一个名为bash-tint的小型帮助程序库,该库在tput之上添加了另一层,使其更易于使用(imho):
示例: tint "white(Cyan(T)Magenta(I)Yellow(N)Black(T)) is bold(really) easy to use."
#19楼
这是最简单易读的解决方案。 使用bashj( https://sourceforge.net/projects/bashj/ ),您只需选择以下行之一:
#!/usr/bin/bash
W="Hello world!"
echo $W
R=130
G=60
B=190
echo u.colored($R,$G,$B,$W)
echo u.colored(255,127,0,$W)
echo u.red($W)
echo u.bold($W)
echo u.italic($W)
Y=u.yellow($W)
echo $Y
echo u.bold($Y)
如果终端应用程序中有颜色支持,则可以使用256x256x256
种颜色。
#20楼
我刚刚合并了所有解决方案中的好方法,最后得出:
cecho(){
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
# ... ADD MORE COLORS
NC="\033[0m" # No Color
printf "${!1}${2} ${NC}\n"
}
您可以将其称为:
cecho "RED" "Helloworld"
#21楼
参考:
echo_red(){
echo -e "\e[1;31m$1\e[0m"
}
echo_green(){
echo -e "\e[1;32m$1\e[0m"
}
echo_yellow(){
echo -e "\e[1;33m$1\e[0m"
}
echo_blue(){
echo -e "\e[1;34m$1\e[0m"
}
#22楼
这是一个在MacOS终端上工作的实现,用于为PS1设置颜色以及不设置颜色。
有两种实现方式,一种是依靠echo,另一种是依靠printf来动态调用方法而又不会松懈。
这只是一个开始,但功能强大,不会闪烁终端。 现在支持git branch,但是最终可以扩展为做很多事情。
可以在这里找到:
https://github.com/momomo/opensource/blob/master/momomo.com.shell.style.sh
应该可以通过复制和粘贴来工作。 没有依赖关系。
#23楼
要显示不同颜色的消息输出,可以使:
echo -e "\033[31;1mYour Message\033[0m"
-黑色0; 30深灰色1; 30
-红色0; 31浅红色1; 31
-绿色0; 32浅绿色1; 32
-棕色/橙色0; 33黄色1; 33
-蓝色0; 34浅蓝色1; 34
-紫色0; 35浅紫色1; 35
-青色0; 36浅青色1; 36
-浅灰色0; 37白色1; 37
#24楼
如果您使用的是zsh
或bash
black() {
echo -e "\e[30m${1}\e[0m"
}
red() {
echo -e "\e[31m${1}\e[0m"
}
green() {
echo -e "\e[32m${1}\e[0m"
}
yellow() {
echo -e "\e[33m${1}\e[0m"
}
blue() {
echo -e "\e[34m${1}\e[0m"
}
magenta() {
echo -e "\e[35m${1}\e[0m"
}
cyan() {
echo -e "\e[36m${1}\e[0m"
}
gray() {
echo -e "\e[90m${1}\e[0m"
}
black 'BLACK'
red 'RED'
green 'GREEN'
yellow 'YELLOW'
blue 'BLUE'
magenta 'MAGENTA'
cyan 'CYAN'
gray 'GRAY'
#25楼
从线程混合其他解决方案后,这就是我如何在npm scripts
输出(gitbash CLI)中获取颜色的方法:
{
"deploy": "echo \u001b[1;32m && ng build && echo \u001b[1;0mdeploy {\u001b[1;33mcopy\u001b[1;0m: \u001b[1;32m0% && cp -r -f dist/packaged/* \\\\SERVER-01\\dist\\ && echo \u001b[1;0mdeploy {\u001b[1;33mcopy\u001b[1;0m} \u001b[1;34m\u001b[1;1m100% DEPLOYED"
}
#26楼
您可以在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'
然后使用它们以您需要的颜色进行打印:
printf "%s\n" "Text in ${red}red${end}, white and ${blu}blue${end}."
#27楼
echo -e "\033[31m Hello World"
[31m
控制文本颜色:
-
30
-37
套前景色 -
40
-47
套背景颜色
可以在此处找到更完整的颜色代码列表。
优良作法是在字符串末尾将文本颜色重置回\\033[0m
。
#28楼
使用具有setaf
功能和参数1
tput
。
echo "$(tput setaf 1)Hello, world$(tput sgr0)"
#29楼
您可以使用以下ANSI转义码 :
Black 0;30 Dark Gray 1;30
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
Cyan 0;36 Light Cyan 1;36
Light Gray 0;37 White 1;37
然后在脚本中像这样使用它们:
# .---------- constant part!
# vvvv vvvv-- the code from above
RED='\033[0;31m'
NC='\033[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow\n"
用红色印出love
。
根据@ james-lim的注释, 如果使用的是echo
命令,请确保使用-e标志以允许反斜杠转义 。
# Continued from above example
echo -e "I ${RED}love${NC} Stack Overflow"
(除非要添加其他空行,否则在使用echo时请勿添加"\\n"
)