我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
当前回答
为了进一步解释这个答案,对于我们这些懒惰的人来说:
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"
其他回答
red='\e[0;31m'
NC='\e[0m' # No Color
echo -e "${red}Hello Stackoverflow${NC}"
这个答案是正确的,只是对颜色的调用不应该在引号内。
echo -e ${red}"Hello Stackoverflow"${NC}
应该会成功的。
这里有一个简单的脚本,可以轻松管理bashshellpromt中的文本样式:
https://github.com/ferromauro/bash-palette
使用以下方法导入代码:
source bash-palette.sh
在echo命令中使用导入的变量(使用-e选项!):
echo -e ${PALETTE_GREEN}Color Green${PALETTE_RESET}
可以组合更多元素:
echo -e ${PALETTE_GREEN}${PALETTE_BLINK}${PALETTE_RED_U}Green Blinking Text over Red Background${PALETTE_RESET}
我刚刚将所有解决方案中的好捕获合并在一起,最终得出:
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"
只为一个回声改变颜色的一个简单方法是定义这样的函数:
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
或者你可以直接使用德鲁回答中提到的颜色代码:
coloredEcho "This text is green" 2
如果您使用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'
联机尝试