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

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


当前回答

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

其他回答

使用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"

为了可读性

如果要提高代码的可读性,可以先回显字符串,然后使用sed添加颜色:

echo 'Hello World!' | sed $'s/World/\e[1m&\e[0m/' 

我刚刚将所有解决方案中的好捕获合并在一起,最终得出:

cecho(){
    RED="\033[0;31m"
    GREEN="\033[0;32m"  # <-- [0 means not bold
    YELLOW="\033[1;33m" # <-- [1 means bold
    CYAN="\033[1;36m"
    # ... Add more colors if you like

    NC="\033[0m" # No Color

    # printf "${(P)1}${2} ${NC}\n" # <-- zsh
    printf "${!1}${2} ${NC}\n" # <-- bash
}

你可以称之为:

cecho "RED" "Helloworld"

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