Chinaunix首页 | 论坛 | 博客
  • 博客访问: 90150
  • 博文数量: 48
  • 博客积分: 1980
  • 博客等级: 上尉
  • 技术积分: 500
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-16 15:03
文章分类

全部博文(48)

文章存档

2009年(48)

我的朋友
最近访客

分类:

2009-09-17 18:35:46

1.命令序列传递

一个here document就是一段带有特殊目的的代码段. 它使用的形式将一个命令序列传递到一个交互程序或者命令中, 比如, , 或者ex文本编辑器.

  1 #!/bin/bash
  2 interactive-program <

注意,某些情况下, 把here document用在非交互工具或命令中, 也会取得非常好的效果, 比如, .


例子 17-1. 广播: 将消息发送给每个登陆的用户

  1 #!/bin/bash
  2 
  3 wall <

 

2 抑制文本行首的TAB,但不是空格

-选项用来标记here document的limit string (<<-LimitString), 可以抑制输出时前边的tab(不是空格). 这么做可以增加一个脚本的可读性.


例子 17-4. 带有抑制tab功能的多行消息

  1 #!/bin/bash
  8 cat <<-ENDOFMESSAGE
  9 	This is line 1 of the message.
 10 	This is line 2 of the message.
 11 	This is line 3 of the message.
 12 	This is line 4 of the message.
 13 	This is the last line of the message.
 14 ENDOFMESSAGE
 23 exit 0

3.支持参数和命令替换

here document支持参数和命令替换. 所以也可以给here document的消息体传递不同的参数, 这样相应的也会修改输出.

 

4.关闭参数替换

在here document的开头, 引用或转义"limit string", 会使得here document消息体中的参数替换被禁用. 即cat << 'endofmessage'

禁用了参数替换后, 将允许输出文本本身(译者注: 就是未转义的原文). 如果你想产生脚本甚至是程序代码的话, 那么可以使用这种办法.

5.here document的输出保存到变量中
也可以将here document的输出保存到变量中.
  1 variable=$(cat <

A here document can supply input to a function in the same script.


6. 给函数提供输入

  1 #!/bin/bash
  2 # here-function.sh
  3 
  4 GetPersonalData ()
  5 {
  6   read firstname
  7   read lastname
  8   read address
  9   read city 
 10   read state 
 11   read zipcode
 12 } # 这个函数看起来就是一个交互函数, 但是... 
 13 
 14 
 15 # 给上边的函数提供输入.
 16 GetPersonalData <

 

Caution

某些工具是不能放入here document中运行的.

Warning

结尾的limit string, 就是here document最后一行的limit string, 必须从第一个字符开始. 它的前面不能够有任何前置的空白. 而在这个limit string后边的空白也会引起异常. 空白将会阻止limit string的识别. (译者注: 下边这个脚本由于结束limit string的问题, 造成脚本无法结束, 所有内容全部被打印出来, 所以注释就不译了, 保持这个例子脚本的原样.)

对于那些使用"here document", 并且非常复杂的任务, 最好考虑使用expect脚本语言, 这种语言就是为了达到向交互程序添加输入的目的而量身定做的.

阅读(717) | 评论(0) | 转发(0) |
0

上一篇:文件描述符

下一篇:here string 用法

给主人留下些什么吧!~~