食品级氢氧化钠:echo问题

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 00:24:05
echo问题
e c h o语句的使用类型依赖于使用的系统是L I N U X、B S D还是系统V,本书对此进行了讲解。
下面创建一个函数决定使用哪种e c h o语句。
使用e c h o时,提示应放在语句末尾,以等待从r e a d命令中接受进一步输入。
L I N U X和B S D为此使用e c h o命令- n选项。
以下是L I N U X(B S D)e c h o语句实例,这里提示放于e c h o后面:
$ echo -n "Your name :"
Your name :{{?}}

系统V使用\ C保证在末尾提示:
echo "Your name :\C"
Your name :?

在e c h o语句开头L I N U X使用- e选项反馈控制字符。其他系统使用反斜线保证s h e l l获知控
制字符的存在。
有两种方法测试e c h o语句类型,下面讲述这两种方法,这样,就可以选择使用其中一个。
第一种方法是在e c h o语句里包含测试控制字符。如果键入\ 0 0 7和一个警铃,表明为系统V,
如果只键入\ 0 0 7,显示为L I N U X。
以下为第一个控制字符测试函数。
  1. uni_prompt()
  2. {
  3.         if [ `echo "\007"` == "\007" ] >/dev/null 2>&1
  4.                 # does a bell sound or are the characters just echoed??
  5.         then   
  6.                 # characters echoed, it's LINUX/BSD
  7.                 echo -e -n "$@"
  8.         else   
  9.                 # it's System V
  10.                 echo "$@\c"
  11.         fi      
  12. }      
复制代码注意这里又用到了特殊变量$ @以反馈字符串,要在脚本中调用上述函数,可以使用:
uni_prompt "\007 there goes the bell ,What is your name:"
这将发出警报并反馈‘ What is your name:’,并在行尾显示字符串。如果在末尾出现字
符,则为系统V版本,否则为L I N U X / B S D版本。
第二种方法使用系统V \c测试字母z是否悬于行尾。
  1. uni_prompt()
  2. # uni_prompt
  3. # univeral prompt
  4. {
  5.         if [ `echo "Z\c"` == "Z" ] >/dev/null 2>&1
  6.                 # echo any character out, does it hang on to the end of line ??
  7.         then   
  8.                 # yes, it's System V
  9.                 echo "$@\c"
  10.         else   
  11.                 # No, it's LINUX, BSD
  12.                 echo -e -n "$@"
  13.         fi      
  14. }      
复制代码要在脚本中调用上述函数,可以使用:
uni_prompts "\007 there goes the ,What is your name:"
使用两个函数中任意一个,并加入一小段脚本:
uni_prompt "\007 There goes the bell, What is your name :"
read NAME
将产生下列输出:
There goes the be,What is your name:

3. 读单个字符

在菜单中进行选择时,最麻烦的工作是必须在选择后键入回车键,或显示“ press any key
to continue”。可以使用d d命令解决不键入回车符以发送击键序列的问题。
d d命令常用于对磁带或一般的磁带解压任务中出现的数据问题提出质疑或转换,但也可
用于创建定长文件。下面创建长度为1兆的文件m y f i l e。
dd if:/dev/zero of=myfile count=512 bs=2048
d d命令可以翻译键盘输入,可被用来接受多个字符。这里如果只要一个字符, d d命令需
要删除换行字符,这与用户点击回车键相对应。d d只送回车前一个字符。在输入前必须使用
s t t y命令将终端设置成未加工模式,并在d d执行前保存设置,在d d完成后恢复终端设置。
函数如下:
  1. read_a_char()
  2. # read_a_char
  3. {
  4.         # save the settings
  5.         SAVEDSTTY=`stty -g`
  6.         # set terminal raw please
  7.         stty cbreak
  8.         # read and output only one character
  9.         dd if=/dev/tty bs=1 count=1 2> /dev/null
  10.         # retore terminal and restore stty
  11.         stty -cbreak
  12.         stty $SAVEDSTTY
  13. }
复制代码要调用函数,返回键入字符,可以使用命令替换操作,例子如下:
  1. echo -n "Hit Any Key To Continue"
  2. character=`read_a_char`
  3. echo " In case you are wondering you pressed $character"