终端颜色打印

SHELL

在shell脚本中,可以使用echo命令加上一些特殊的转义字符来实现彩色打印,下面是一些常用的彩色打印方式:

红色字体:\033[31m
绿色字体:\033[32m
黄色字体:\033[33m
蓝色字体:\033[34m
紫色字体:\033[35m
青色字体:\033[36m
白色字体:\033[37m

示例代码:

echo -e "\033[31m This is red text \033[0m"
echo -e "\033[32m This is green text \033[0m"
echo -e "\033[33m This is yellow text \033[0m"
echo -e "\033[34m This is blue text \033[0m"
echo -e "\033[35m This is purple text \033[0m"
echo -e "\033[36m This is cyan text \033[0m"
echo -e "\033[37m This is white text \033[0m"

其中\033[0m 表示还原成终端默认颜色。注意需要使用-e选项启用转义字符的解析。

Golang

fatih/color 是一个非常流行的终端彩色打印库,支持 ANSI 转义码和 Windows/Unix 终端的 API,使用非常简单。可以使用 color.New() 函数创建一个 *color.Color 对象,然后使用该对象的方法来设置打印的颜色和样式。

package main

import "github.com/fatih/color"

func main() {
    // 创建一个 Color 对象
    c := color.New(color.FgRed)

    // 设置颜色
    c.Add(color.Bold)

    // 打印带颜色的字符串
    c.Println("Hello, world!")
}

在上面的代码中,我们创建了一个 *color.Color 对象,设置了红色的前景色和加粗样式,并使用 Println() 方法打印了一个带颜色的字符串。

原生封装一个

copyed from: https://www.digitalocean.com/community/tutorials/how-to-use-the-flag-package-in-go

package main

import (
	"flag"
	"fmt"
)

type Color string

const (
	ColorBlack  Color = "\u001b[30m"
	ColorRed          = "\u001b[31m"
	ColorGreen        = "\u001b[32m"
	ColorYellow       = "\u001b[33m"
	ColorBlue         = "\u001b[34m"
	ColorReset        = "\u001b[0m"
)

func colorize(color Color, message string) {
	fmt.Println(string(color), message, string(ColorReset))
}

func main() {
	useColor := flag.Bool("color", false, "display colorized output")
	flag.Parse()

	if *useColor {
		colorize(ColorBlue, "Hello, DigitalOcean!")
		return
	}
	fmt.Println("Hello, DigitalOcean!")
}
posted @ 2023-02-24 10:58  蓝天上的云℡  阅读(53)  评论(0编辑  收藏  举报