免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1463 | 回复: 0
打印 上一主题 下一主题

Bash实现输出彩色文字 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-14 19:39 |只看该作者 |正序浏览

默认情况下,bash输出的字符是颜色比较单调,其实echo有个-e选项可以利用转义符实现彩色的字符输出的
echo
-e "\E[3
前景色编号;4背景色编号m""\033[样式m内容\033[0m"
举例
echo -e
"\E[31;43m\033[4mRed\033[0m"的效果是输出红字黄底色,带下划线的效果
(1)首先解释\E,\033和[ m
   \E[是颜色的控制字符串,两个\E[之间的部分用于控制颜色,3是前景色控制,后面跟的是颜色值(0-9),4是背景色控制,后面跟的是颜色值(0-9),前景色和背景色设定之间使用;分隔开
   \033[和m是样式控制串,两个之间的部分用于控制样式,\033[后面跟样式值(上面的例子中是4表示下划线),然后是m,接着是要彩色显示的文字串,后面是样式设置结束标志\033[0m
(2)下面解释前景色和背景色的颜色对应的编号(0-9)
0  
black
1    red
2    green
3    yellow
4   
blue
5    magenta(洋红色)
6    cyan(青色)
7    gray
8    white
9   
white
(3)样式控制数字编号为(1-9)
1  
   淡些、粗些
4  
   下划线
7  
   反相(颠倒前景色和背景色)
9  
   删除线
2,3,5,6,8    正常

我们现在再来看echo -e
"\E[31;43m\033[4mRed\033[0m"就明白为什么会输出红字黄底带下划线的字了
然而我们可以看出每次要输出彩色文字的时候都要写这么长的乱乱的一个串也够麻烦的,能不能简化一下,一次麻烦长期有效呢?,当然可以我们可以定义函数,甚至可以写好一个shell放到/bin下以后当做系统调用
下面是函数示例
#!/bin/bash
#输出彩色文字,需要四个参数,分别是前景色,背景色,样式,文字
function ColorText()
{
#判断参数个数,更加严格的判断比如是否超过范围这里就不做详细判断了
if [ $# -ne 4  ]
then
    echo "Usage:4 parameters are needed!"
    echo "      ForeColor,BackgroundClor Style and Text!"
    ShowHelp;
else
  Fg="3""$1"
  Bg="4""$2"
  SetColor="\E[""$Fg;$Bg""m"
  Style="\033[""$3""m"
  Text="$4"
  EndStyle="\033[0m"
  echo -e "$SetColor""$Style""$Text""$EndStyle"
fi;
}
#输出帮助信息
function ShowHelp()
{
        echo "The frst parameter is a number ranged from 1 to 10,represents the foreground color."
        echo "The second parameter is  a number ranged from 1 to 10,represents the background color."
        ColorText 1 8 2 "1    red";
        ColorText 2 8 2 "2    green";
        ColorText 3 8 2 "3    yellow";
        ColorText 4 8 2 "4    blue";
        ColorText 5 8 2 "5    magenta";
        ColorText 6 8 2 "6    cyan";
        ColorText 7 8 2 "7    gray";
        ColorText 8 8 2 "8    white";
        ColorText 9 8 2 "9    white";
        ColorText 10 8 2 "10   black";
        echo "The third parameter is a number ranged from 1 to 9,represents the style of the characters."
        ColorText 10 8 1 "1    lighter,and bold";
        ColorText 10 8 4 "4    draw a line under the string.";
        ColorText 10 8 7 "7    swap the foreground color and the background color";
        ColorText 10 8 9 "9    draw a deleting line";
        ColorText 10 8 9 "others  normal style";
        echo "The fourth parameter is the content you wanna clolor,a string."
}
#调用刚刚定义的函数来实现输出彩色文字到屏幕上的功能
#ColorText  2 0 4 "TextToTest Color";#直接调用的方法
ColorText $@;#也可以如此写,这样在运行shell的时候输入需要的四个参数
转:http://wzgyantai.blogbus.com/logs/35899997.html
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93838/showart_1900221.html
  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP