看到Linux系统中好多软件包括系统本身启动的时候打印整整齐齐的[ OK ], [ Failed ],感觉非常舒服。
但是自己写了很多shell程序,提示语句都是简单的echo或printf,最多可以打印个彩色的状态提示。
近来总是写升级包、安装包的脚本,Shell编程也感觉越来越顺手,所以想解决这个问题。
我解决这个问题用了很简单的方法,可能有高人有更加简洁的代码可以实现,但是我写这个代码容易读懂,思想也简单,希望能帮助搜索到这篇博客的童鞋。
基本思想:
用函数Echo实现白色文字加状态提示。
用函数ColorEcho实现彩色文字加状态提示。
状态提示颜色固定。
每行都按66个字符进行对齐。也就是说最后的状态是对齐的,前面写文字,之间是空格。
实现方法为:每次记录当前打印的字符数,如果遇到OK或Failed(大小写区分),就认为当前打印字符数为0,并打印状态信息。
代码如下(可复制使用):
使用时刻保存为单独文件,在别的shell脚本中调用即可,比如存为color_echo.sh以后,同目录下的shell脚本可以这样调用:
. color_echo.sh;
就是一个点,一个空格,加上文件路径,打个冒号(冒号可选,shell语法,有冒号的话,同一行还可以写代码,这个你懂的)。
# 前景色:30(黑色)、31(红色)、32(绿色)、 33(黄色)、34(蓝色)、35(洋红)、36(青色)、37(白色)。 # 背景色:十位换成4 okstatus="[ \033[0;32;40mOK\033[0m ]\n" failstatus="[ \033[0;31;40mFAILED\033[0m ]\n" last_len=0 function Echo() { content=$1 if [[ $content = "OK" ]]; then content=$okstatus content_len=0 elif [[ $content = "Failed" ]]; then content=$failstatus content_len=0 else content_len=${#content} endlen=$content_len ((startlen=endlen-2)) if [[ ${content:$startlen:$endlen} = "\n" ]]; then content_len=0 fi fi if [ $last_len -ne 0 -a $content_len -eq 0 ]; then ((blank_len=66-last_len)) printf "%${blank_len}s" " " fi echo -en "$content" ((last_len=last_len+content_len)) if [ $content_len -eq 0 ]; then ((last_len=0)) fi } function ColorEcho() { color=white if [ $# -ge 2 ]; then color=$1 content=$2 elif [ $# -eq 1 ]; then content=$1 else return fi case $color in black) color=30 ;; red) color=31 ;; green) color=32 ;; yellow) color=33 ;; "blue") color=34 ;; magenta) color=35 ;; cyan) color=36 ;; white) color=37 ;; *) color=0 ;; esac if [[ $content = "OK" ]]; then content=$okstatus content_len=0 elif [[ $content = "Failed" ]]; then content=$failstatus content_len=0 else content_len=${#content} endlen=$content_len ((startlen=endlen-2)) if [[ ${content:$startlen:$endlen} = "\n" ]]; then content_len=0 fi fi if [ $last_len -ne 0 -a $content_len -eq 0 ]; then ((blank_len=66-last_len)) printf "%${blank_len}s" " " fi if [ $color -gt 0 ]; then content="\033[0;${color};40m${content}\033[0m" fi echo -en "$content" ((last_len=last_len+content_len)) if [ $content_len -eq 0 ]; then ((last_len=0)) fi } if [ 0 -gt 1 ]; then Echo "Start to do ... " Echo "OK" Echo "Stop xxx ..." Echo "Failed" fi