Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15936637
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类:

2008-03-21 16:54:22

或许你还不知道你的标准终端应用是能够支持显示不同风格的文本。你是否想让一些词在你的脚本里展示有个性 的,比如是字体是红色,并有个黄色的背景作衬托呢?但是,如果你通过使用(美国国家标准学会)序列去作这些变化可能很难的,因为这些序列让用户觉 得很不友好。因此,本章这个脚本就要创建一些变量,它们的值代表ANSI代码,即可以打开和关闭各种颜色和格式显示功能。

脚本源代码
#!/bin/sh

# ANSI Color -- 使用这些变量让输出有各种颜色。
# and formats. Color names that end with 'f' are foreground (text) colors,
# and those ending with 'b' are background colors.

initializeANSI()
{
  esc="\033" # if this doesn't work, enter an ESC directly

  blackf="${esc}[30m";   redf="${esc}[31m";    greenf="${esc}[32m"
  yellowf="${esc}[33m"   bluef="${esc}[34m";   purplef="${esc}[35m"
  cyanf="${esc}[36m";    whitef="${esc}[37m"

  blackb="${esc}[40m";   redb="${esc}[41m";    greenb="${esc}[42m"
  yellowb="${esc}[43m"   blueb="${esc}[44m";   purpleb="${esc}[45m"
  cyanb="${esc}[46m";    whiteb="${esc}[47m"

  boldon="${esc}[1m";    boldoff="${esc}[22m"
  italicson="${esc}[3m"; italicsoff="${esc}[23m"
  ulon="${esc}[4m";      uloff="${esc}[24m"
  invon="${esc}[7m";     invoff="${esc}[27m"

  reset="${esc}[0m"
}

工作原理
如果您有使用过HTML,你可能会对这些序列的工作方式觉得点莫名其妙的。在HTML里,你要在对面代码打开和关闭修饰语,你必须先关闭掉打开修饰语。所以要在一个句子显示有个性的词语,你可以使用下面的HTML代码:
this is in bold and this is italics within the bold
关闭标签而没有关闭斜体字的将会对网络浏览器造成影响。而通过ANSI颜色序列,一些修饰语能够取代以前部分修饰语,还可以用简单的序列重设关闭所有修饰语。基于ANSI 序列,你必须先设置ANSI颜色序列后再输出。使用该脚本里的变量,你可以写下先前序列:
${boldon}this is in bold and ${italicson}this is
italics${italicsoff}within the bold${reset}

运行脚本
要执行该脚本,我们需要设定所有ANSI序列

 

initializeANSI

cat << EOF
${yellowf}This is a phrase in yellow${redb} and red${reset}
${boldon}This is bold${ulon} this is italics${reset} bye bye
${italicson}This is italics${italicsoff} and this is not
${ulon}This is ul${uloff} and this is not
${invon}This is inv${invoff} and this is not
${yellowf}${redb}Warning I ${yellowb}${redf}Warning II${reset}
EOF

结果

This is a phrase in yellow and red
This is bold this is italics bye bye
This is italics and this is not
This is ul and this is not
This is inv and this is not
Warning I Warning II

改进与加强
当你使用此脚本时,你可能看到类似下面的内容:
\033[33m\033[41mWarning!\033[43m\033[31mWarning!\033[0m
如果有的话,那可能是你的终端或窗口不支持ANSI颜色序列,

如果,在另一方面,你的终端或窗口,不支持ANSI颜色序列,你可能会想升级,使您可以添加颜色和类型面对面增强输出到其他脚本。

阅读(1381) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~