Background
在编写比较复杂的脚本时,需要输出相关日志信息,方便知悉脚本的执行情况以及问题的排查。
源码 log.sh
# 自定义日志函数
function log(){if [[ $1 = "i" || $1 = "info" ]]; thenecho -ne "\033[1;34mINFO: \033[0m"shift && echo -e "$@"elif [[ $1 = "w" || $1 = "warn" ]]; thenecho -ne "\033[1;33mWARN: \033[0m"shift && echo -e "$@"elif [[ $1 = "s" || $1 = "success" ]]; thenecho -ne "\033[1;32mSUCCESS: \033[0m"shift && echo -e "$@"elif [[ $1 = "e" || $1 = "error" ]]; thenecho -ne "\033[1;31mERROR: \033[0m"shift && echo -e "$@"elsecolors=$1input=$2opt='-e'rightpattern='true'if [[ ${colors:0:1} = "n" ]]; thencolors=${colors//n/}opt='-ne'fiif [[ $colors =~ "," ]]; thencolorarr=${colors//,/ }colors=${colors//,/;}for color in ${colorarr[@]};doif ! [[ $color =~ ^[0-9]+$ && $color -gt 0 && $color -lt 49 ]]; thenrightpattern='false'fidoneelseif ! [[ $colors =~ ^[0-9]+$ && $colors -gt 0 && $colors -lt 49 ]]; thenrightpattern='false'fifiif [[ -n $input && $rightpattern = 'true' ]]; thenshift && str="$@"echo $opt "\033[${colors}m${str}\033[0m"elsestr="$@"echo $opt "${str}"fifi
}log $@
使用
- 输出
i-提示、w-告警、s-成功和e-错误信息
sh log.sh i wlf is a coder
sh log.sh w wlf is a coder
sh log.sh s wlf is a coder
sh log.sh e wlf is a coder

- 直接输出字符串,和
echo功能一样
sh log.sh wlf is a coder
sh log.sh 'wlf is a coder'

- 输入参数第一个字符为
n则不换行输出,相当于echo -n
sh log.sh nwlf is a coder

- 输入字体设置序号设置输出字体
sh log.sh 33 wlf is a coder
sh log.sh n33 wlf is a coder
sh log.sh 333 wlf is a coder

- 多种格式英文分号
,分隔
sh log.sh 4,33 wlf is a coder
sh log.sh n4,33 wlf is a coder
sh log.sh 4,333 wlf is a coder

字体设置表
| 序号 | 设置 |
|---|---|
| 0 | 重新设置属性到缺省设置 |
| 1 | 设置粗体 |
| 2 | 设置一半亮度(模拟彩色显示器的颜色) |
| 4 | 设置下划线(模拟彩色显示器的颜色) |
| 5 | 设置闪烁 |
| 7 | 设置反向图象 |
| 22 | 设置一般密度 |
| 24 | 关闭下划线 |
| 25 | 关闭闪烁 |
| 27 | 关闭反向图象 |
| 30 | 设置黑色前景 |
| 31 | 设置红色前景 |
| 32 | 设置绿色前景 |
| 33 | 设置棕色前景 |
| 34 | 设置蓝色前景 |
| 35 | 设置紫色前景 |
| 36 | 设置青色前景 |
| 37 | 设置白色前景 |
| 38 | 在缺省的前景颜色上设置下划线 |
| 39 | 在缺省的前景颜色上关闭下划线 |
| 40 | 设置黑色背景 |
| 41 | 设置红色背景 |
| 42 | 设置绿色背景 |
| 43 | 设置棕色背景 |
| 44 | 设置蓝色背景 |
| 45 | 设置紫色背景 |
| 46 | 设置青色背景 |
| 47 | 设置白色背景 |
| 49 | 设置缺省黑色背景 |