我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
当前回答
如果您使用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'
联机尝试
其他回答
灵感来自@nachoparker的回答,我的.bashrc中有这个:
#### colours
source xcol.sh
### tput foreground
export tpfn=$'\e[0m' # normal
export tpfb=$(tput bold)
## normal colours
export tpf0=$(tput setaf 0) # black
export tpf1=$(tput setaf 1) # red
export tpf2=$(tput setaf 2) # green
export tpf3=$(tput setaf 3) # yellow
export tpf4=$(tput setaf 4) # blue
export tpf5=$(tput setaf 5) # magenta
export tpf6=$(tput setaf 6) # cyan
export tpf7=$(tput setaf 7) # white
# echo "${tpf0}black ${tpf1}red ${tpf2}green ${tpf3}yellow ${tpf4}blue ${tpf5}magenta ${tpf6}cyan ${tpf7}white${tpfn}"
## bold colours
export tpf0b="$tpfb$tpf0" # bold black
export tpf1b="$tpfb$tpf1" # bold red
export tpf2b="$tpfb$tpf2" # bold green
export tpf3b="$tpfb$tpf3" # bold yellow
export tpf4b="$tpfb$tpf4" # bold blue
export tpf5b="$tpfb$tpf5" # bold magenta
export tpf6b="$tpfb$tpf6" # bold cyan
export tpf7b="$tpfb$tpf7" # bold white
# echo "${tpf0b}black ${tpf1b}red ${tpf2b}green ${tpf3b}yellow ${tpf4b}blue ${tpf5b}magenta ${tpf6b}cyan ${tpf7b}white${tpfn}"
出口允许我使用这些tpf。。在Bash脚本中。
echo -e "\033[31m Hello World"
[31m控制文本颜色:
30-37套前景色40-47套背景色
这里可以找到更完整的颜色代码列表。
最好将字符串末尾的文本颜色重置回\033[0m。
您可以“组合”颜色和文本模式。
#!/bin/bash
echo red text / black background \(Reverse\)
echo "\033[31;7mHello world\e[0m";
echo -e "\033[31;7mHello world\e[0m";
echo
echo yellow text / red background
echo "\033[32;41mHello world\e[0m";
echo -e "\033[32;41mHello world\e[0m";
echo "\033[0;32;41mHello world\e[0m";
echo -e "\033[0;32;41mHello world\e[0m";
echo
echo yellow BOLD text / red background
echo "\033[1;32;41mHello world\e[0m";
echo -e "\033[1;32;41mHello world\e[0m";
echo
echo yellow BOLD text underline / red background
echo "\033[1;4;32;41mHello world\e[0m";
echo -e "\033[1;4;32;41mHello world\e[0m";
echo "\033[1;32;4;41mHello world\e[0m";
echo -e "\033[1;32;4;41mHello world\e[0m";
echo "\033[4;32;41;1mHello world\e[0m";
echo -e "\033[4;32;41;1mHello world\e[0m";
echo
为了可读性
如果要提高代码的可读性,可以先回显字符串,然后使用sed添加颜色:
echo 'Hello World!' | sed $'s/World/\e[1m&\e[0m/'
我应该使用tput,而不是硬编码特定于当前终端的转义码。
这是我最喜欢的演示脚本:
#!/bin/bash
tput init
end=$(( $(tput colors)-1 ))
w=8
for c in $(seq 0 $end); do
eval "$(printf "tput setaf %3s " "$c")"; echo -n "$_"
[[ $c -ge $(( w*2 )) ]] && offset=2 || offset=0
[[ $(((c+offset) % (w-offset))) -eq $(((w-offset)-1)) ]] && echo
done
tput init