定义自己的echo打印风格

1、概述

echo 命令是 Linux 中最基本和最常用的命令之一。 传递给 echo 的参数被打印到标准输出中。我们可以用它输出字符串提示:

[root@others ~]# echo "hello"
hello

也可以用来输出变量值

[root@others ~]# a="this is a test"
[root@others ~]# echo $a
this is a test
[root@others ~]# b=2023
[root@others ~]# echo $b
2023

我们可以自定义函数,进行简单的封装,使用echo输出不同颜色文本

2、具体封装的实现

详情加下面脚本:

文件: my_utils.sh

#!/bin/bash
# create by liu.bo ,since 2023.06.15
# 我自己的通用函数集合


#------定义自己的打印风格---------------

ECHO_BEGIN_INFO="\033[32m"     # green characters
ECHO_BEGIN_WARN="\033[35m"     # purple characters
ECHO_BEGIN_ERROR="\033[41;37m" # white characters on red background
ECHO_END="\033[0m"

echo_info()
{
    echo -e "${ECHO_BEGIN_INFO}$1${ECHO_END}"
}

echo_warn()
{
    echo -e "${ECHO_BEGIN_WARN}$1${ECHO_END}"
}

echo_error()
{
    echo -e "${ECHO_BEGIN_ERROR}$1${ECHO_END}"
}

3、封装函数的使用

先source一下上面的功能文件 my_utils.sh,就可以使用里面自定义的打印函数,用法如下:

[root@others liu.bo]# source my_utils.sh 
[root@others liu.bo]# echo_info test
test
[root@others liu.bo]# echo_warn test
test
[root@others liu.bo]# echo_error test
test

上述代码块不能看到运行效果,截图如下,通过自定义颜色:绿色、紫色和红色,来显示info,warning,erro,可以非常的直观。

4、技术总结

echo加上激活转义字符 -e

使用-e选项时,若字符串中出现以下字符,则特别加以处理,而不会将它当成一般文字输出

字背景颜色范围:40----49 
40:黑 
41:深红 
42:绿 
43:黄色 
44:蓝色 
45:紫色 
46:深绿 
47:白色 

字颜色:30-----------39 
30:黑 
31:红 
32:绿 
33:黄 
34:蓝色 
35:紫色 
36:深绿 
37:白色 

==========ANSI控制码的说明 
\33[0m 关闭所有属性 
\33[1m 设置高亮度 
\33[4m 下划线 
\33[5m 闪烁 
\33[7m 反显 
\33[8m 消隐 
\33[30m -- \33[37m 设置前景色 
\33[40m -- \33[47m 设置背景色 
\33[nA 光标上移n行 
\33[nB 光标下移n行 
\33[nC 光标右移n行 
\33[nD 光标左移n行 
\33[y;xH设置光标位置 
\33[2J 清屏 
\33[K 清除从光标到行尾的内容 
\33[s 保存光标位置 
\33[u 恢复光标位置 
\33[?25l 隐藏光标 
\33[?25h 显示光标

一些特效:绿色背景,红色闪烁

[root@others ~]# echo -e "\e[1;42mGreed Background\e[0m"
Greed Background
[root@others ~]# echo -e "\033[37;31;5mMySQL Server Stop...\033[39;49;0m"
MySQL Server Stop...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值