我正在尝试使用echo命令在终端中打印文本。

我想用红色打印文本。我该怎么做?


当前回答

我对托拜厄斯回答的重复:

# Color
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

function red {
    printf "${RED}$@${NC}\n"
}

function green {
    printf "${GREEN}$@${NC}\n"
}

function yellow {
    printf "${YELLOW}$@${NC}\n"
}

其他回答

red='\e[0;31m'
NC='\e[0m' # No Color
echo -e "${red}Hello Stackoverflow${NC}"

这个答案是正确的,只是对颜色的调用不应该在引号内。

echo -e ${red}"Hello Stackoverflow"${NC}

应该会成功的。

我应该使用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

灵感来自@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脚本中。

您绝对应该在原始ANSI控制序列上使用tput。

因为有大量不同的终端控制语言,通常系统有一个中间通信层。在数据库中查找当前检测到的真实代码终端类型,并向API或(来自shell)转换为命令。其中一个命令是tput。tput接受一组名为功能名称和任何参数(如果合适),然后查找终端中检测到的终端的正确转义序列数据库并打印正确的代码(希望终端理解)。

从…起http://wiki.bash-hackers.org/scripting/terminalcodes

也就是说,我编写了一个名为bash tint的小助手库,它在tput之上添加了另一层,使其使用起来更加简单(imho):

例子:tint“白色(青色(T)洋红色(I)黄色(N)黑色(T))粗体(真的)易于使用。”

将给出以下结果:

如果您使用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'

联机尝试