19 嵌入文档

Here and now, boys.     —Aldous Huxley, Island

嵌入文档是一段有特殊作用的代码块,它用 I/O 重定向 在交互程序和交互命令中传递和反馈一个命令列表,例如 ftp,cat 或者是 ex 文本编辑器

1. COMMAND <<InputComesFromHERE
2. ...
3. ...
4. ...
5. InputComesFromHERE

嵌入文档用限定符作为命令列表的边界,在限定符前需要一个指定的标识符 <<,这会将一个程序或命令的标准输入(stdin)进行重定向,它类似 交互程序 < 命令文件 的方式,其中命令文件内容如下

1. command #1
2. command #2
3. ...

嵌入文档的格式大致如下

1. interactive-program <<LimitString
2. command #1
3. command #2
4. ...
5. LimitString

限定符的选择必须保证特殊以确保不会和命令列表里的内容发生混淆。

注意嵌入文档有时候用作非交互的工具和命令有着非常好的效果,例如 wall

样例 19-1. broadcast: 给每个登陆者发送信息

1. #!/bin/bash

3. wall <<zzz23EndOfMessagezzz23
4. E-mail your noontime orders for pizza to the system administrator.
5. (Add an extra dollar for anchovy or mushroom topping.)
6. # 额外的信息文本.
7. # 注意: 'wall' 会打印注释行.
8. zzz23EndOfMessagezzz23

10. # 更有效的做法是通过
11. #         wall < 信息文本
12. #  然而, 在脚本里嵌入信息模板不乏是一种迅速而又随性的解决方式.

14. exit

样例: 19-2. dummyfile:创建一个有两行内容的虚拟文件

1. #!/bin/bash

3. # 非交互的使用 `vi` 编辑文件.
4. # 仿照 'sed'.

6. E_BADARGS=85

8. if [ -z "$1" ]
9. then
10. echo "Usage: `basename $0` filename"
11. exit $E_BADARGS
12. fi

14. TARGETFILE=$1

16. # 插入两行到文件中保存
17. #--------Begin here document-----------#
18. vi $TARGETFILE <<x23LimitStringx23
19. i
20. This is line 1 of the example file.
21. This is line 2 of the example file.
22. ^[
23. ZZ
24. x23LimitStringx23
25. #----------End here document-----------#

27. #  注意 "^" 对 "[" 进行了转义
28. #+ 这段起到了和键盘上按下 Control-V <Esc> 相同的效果.

30. #  Bram Moolenaar 指出这种情况下 'vim' 可能无法正常工作
31. #+ 因为在与终端交互的过程中可能会出现问题.

33. exit

上述脚本实现了 ex 的功能, 而不是 vi. 嵌入文档包含了 ex 足够通用的命令列表来形成自有的类别, 所以又称之为 ex 脚本.

1. #!/bin/bash
2. #  替换所有的以 ".txt" 后缀结尾的文件的 "Smith" 为 "Jones"

4. ORIGINAL=Smith
5. REPLACEMENT=Jones

7. for word in $(fgrep -l $ORIGINAL *.txt)
8. do
9. # -------------------------------------
10. ex $word <<EOF
11. :%s/$ORIGINAL/$REPLACEMENT/g
12. :wq
13. EOF
14. # :%s is the "ex" substitution command.
15. # :wq is write-and-quit.
16. # -------------------------------------
17. done

类似的 ex 脚本 是 cat 脚本.

样例 19-3. 使用 cat 的多行信息

1. #!/bin/bash

3. #  'echo' 可以输出单行信息,
4. #+  但是如果是输出消息块就有点问题了.
5. #   'cat' 嵌入文档却能解决这个局限.

7. cat <<End-of-message
8. -------------------------------------
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. -------------------------------------
15. End-of-message

17. #  替换上述嵌入文档内的 7 行文本
18. #+   cat > $Newfile <<End-of-message
19. #+       ^^^^^^^^^^
20. #+ 将输出追加到 $Newfile, 而不是标准输出.

22. exit 0

25. #--------------------------------------------
26. # 由于上面的 "exit 0",下面的代码将不会生效.

28. # S.C. points out that the following also works.
29. echo "-------------------------------------
30. This is line 1 of the message.
31. This is line 2 of the message.
32. This is line 3 of the message.
33. This is line 4 of the message.
34. This is the last line of the message.
35. -------------------------------------"
36. # 然而, 文本可能不包括双引号除非出现了字符串逃逸.

- 的作用是标记了一个嵌入文档限制符 (<<-LimitString) ,它能抑制输出的行首的 tab (非空格). 这在脚本可读性方面可能非常有用.

样例 19-4. 抑制 tab 的多行信息

1. #!/bin/bash
2. # 和之前的样例一样, 但...

4. #  嵌入文档内的 '-' ,也就是 <<-
5. #+ 抑制了文档行首的 'tab',
6. #+ 但 *不是* 空格.

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
15. # 脚本的输出将左对齐.
16. # 行首的 tab 将不会输出.

18. # 上面 5 行的 "信息" 以 tab 开始, 不是空格.
19. # 空格不会受影响 <<- .

21. # 注意这个选项对 *内嵌的* tab 没有影响.

23. exit 0

嵌入文档支持参数和命令替换. 因此可以向嵌入文档传递不同的参数,变向的改其输出.

样例 19-5. 可替换参数的嵌入文档

1. #!/bin/bash
2. # 另一个使用参数替换的 'cat' 嵌入文档.

4. # 试一试没有命令行参数,   ./scriptname
5. # 试一试一个命令行参数,   ./scriptname Mortimer
6. # 试试用一两个单词引用命令行参数,
7. #                           ./scriptname "Mortimer Jones"

9. CMDLINEPARAM=1     #  Expect at least command-line parameter.

11. if [ $# -ge $CMDLINEPARAM ]
12. then
13. NAME=$1          #  If more than one command-line param,
14. #+ then just take the first.
15. else
16. NAME="John Doe"  #  Default, if no command-line parameter.
17. fi

19. RESPONDENT="the author of this fine script"

22. cat <<Endofmessage

24. Hello, there, $NAME.
25. Greetings to you, $NAME, from $RESPONDENT.

27. # 这个注释在输出时显示 (为什么?).

29. Endofmessage

31. # 注意输出了空行.
32. # 所以可以这样注释.

34. exit

这个包含参数替换的嵌入文档是相当有用的

样例 19-6. 上传文件对到 Sunsite 入口目录

1. #!/bin/bash
2. # upload.sh

4. #  上传文件对 (Filename.lsm, Filename.tar.gz)
5. #+ 到 Sunsite/UNC (ibiblio.org) 的入口目录.
6. #  Filename.tar.gz 是个 tarball.
7. #  Filename.lsm is 是个描述文件.
8. #  Sunsite 需要 "lsm" 文件, 否则将会退回给发送者

11. E_ARGERROR=85

13. if [ -z "$1" ]
14. then
15. echo "Usage: `basename $0` Filename-to-upload"
16. exit $E_ARGERROR
17. fi

20. Filename=`basename $1`           # Strips pathname out of file name.

22. Server="ibiblio.org"
23. Directory="/incoming/Linux"
24. #  脚本里不需要硬编码,
25. #+ 但最好可以替换命令行参数.

27. Password="your.e-mail.address"   # Change above to suit.

29. ftp -n $Server <<End-Of-Session
30. # -n 禁用自动登录

32. user anonymous "$Password"       #  If this doesn't work, then try:
33. #  quote user anonymous "$Password"
34. binary
35. bell                             # Ring 'bell' after each file transfer.
36. cd $Directory
37. put "$Filename.lsm"
38. put "$Filename.tar.gz"
39. bye
40. End-Of-Session

42. exit 0

在嵌入文档头部引用或转义”限制符”来禁用参数替换.原因是 引用/转义 限定符能有效的转义 “$”, “`”, 和 “\” 这些特殊符号, 使他们维持字面上的意思. (感谢 Allen Halsey 指出这点.)

样例 19-7. 禁用参数替换

1. #!/bin/bash
2. #  A 'cat' here-document, but with parameter substitution disabled.

4. NAME="John Doe"
5. RESPONDENT="the author of this fine script"

7. cat <<'Endofmessage'

9. Hello, there, $NAME.
10. Greetings to you, $NAME, from $RESPONDENT.

12. Endofmessage

14. #   当'限制符'引用或转义时不会有参数替换.
15. #   下面的嵌入文档也有同样的效果
16. #   cat <<"Endofmessage"
17. #   cat <<\Endofmessage

21. #   同样的:

23. cat <<"SpecialCharTest"

25. Directory listing would follow
26. if limit string were not quoted.
27. `ls -l`

29. Arithmetic expansion would take place
30. if limit string were not quoted.
31. $((5 + 3))

33. A a single backslash would echo
34. if limit string were not quoted.
35. \\

37. SpecialCharTest

40. exit

生成脚本或者程序代码时可以用禁用参数的方式来输出文本.

样例 19-8. 生成其他脚本的脚本

1. #!/bin/bash
2. # generate-script.sh
3. # Based on an idea by Albert Reiner.

5. OUTFILE=generated.sh         # Name of the file to generate.

8. # -----------------------------------------------------------
9. # '嵌入文档涵盖了生成脚本的主体部分.
10. (
11. cat <<'EOF'
12. #!/bin/bash

14. echo "This is a generated shell script."
15. #  注意我们现在在一个子 shell 内,
16. #+ 我们不能访问 "外部" 脚本变量.

18. echo "Generated file will be named: $OUTFILE"
19. #  上面这行并不能按照预期的正常工作
20. #+ 因为参数扩展已被禁用.
21. #  相反的, 结果是文字输出.

23. a=7
24. b=3

26. let "c = $a * $b"
27. echo "c = $c"

29. exit 0
30. EOF
31. ) > $OUTFILE
32. # -----------------------------------------------------------

34. #  在上述的嵌入文档内引用'限制符'防止变量扩展

36. if [ -f "$OUTFILE" ]
37. then
38. chmod 755 $OUTFILE
39. # 生成可执行文件.
40. else
41. echo "Problem in creating file: \"$OUTFILE\""
42. fi

44. #  这个方法适用于生成 C, Perl, Python, Makefiles 等等

46. exit 0

可以从嵌入文档的输出设置一个变量的值. 这实际上是种灵活的 命令替换.

1. variable=$(cat <<SETVAR
2. This variable
3. runs over multiple lines.
4. SETVAR
5. )

7. echo "$variable"

同样的脚本里嵌入文档可以作为函数的输入.

样例 19-9. 嵌入文档和函数

1. #!/bin/bash
2. # here-function.sh

4. GetPersonalData ()
5. {
6. read firstname
7. read lastname
8. read address
9. read city
10. read state
11. read zipcode
12. } # 可以肯定的是这应该是个交互式的函数, 但 . . .

15. # 作为函数的输入.
16. GetPersonalData <<RECORD001
17. Bozo
18. Bozeman
19. 2726 Nondescript Dr.
20. Bozeman
21. MT
22. 21226
23. RECORD001

26. echo
27. echo "$firstname $lastname"
28. echo "$address"
29. echo "$city, $state $zipcode"
30. echo

32. exit 0

可以这样使用: 作为一个虚构的命令接受嵌入文档的输出. 这样实际上就创建了一个 “匿名” 嵌入文档.

样例 19-10. “匿名” 嵌入文档

1. #!/bin/bash

3. : <<TESTVARIABLES
4. ${HOSTNAME?}${USER?}${MAIL?}  # Print error message if one of the variables not set.
5. TESTVARIABLES

7. exit $?
  • 上面技巧的一种变体允许 “可添加注释” 的代码块.

样例 19-11. 可添加注释的代码块

1. #!/bin/bash
2. # commentblock.sh

4. : <<COMMENTBLOCK
5. echo "This line will not echo."
6. 这些注释没有 "#" 前缀.
7. 则是另一种没有 "#" 前缀的注释方法.

9. &*@!!++=
10. 上面这行不会产生报错信息,
11. 因为 bash 解释器会忽略它.

13. COMMENTBLOCK

15. echo "Exit value of above \"COMMENTBLOCK\" is $?."   # 0
16. # 没有错误输出.
17. echo

19. #  上面的技巧经常用于工作代码的注释用作排错目的
20. #  这省去了在每一行开头加上 "#" 前缀,
21. #+ 然后调试完不得不删除每行的前缀的重复工作.
22. #  注意我们用了 ":", 在这之上,是可选的.

24. echo "Just before commented-out code block."
25. #  下面这个在双破折号之间的代码不会被执行.
26. #  ===================================================================
27. : <<DEBUGXXX
28. for file in *
29. do
30. cat "$file"
31. done
32. DEBUGXXX
33. #  ===================================================================
34. echo "Just after commented-out code block."

36. exit 0

40. ######################################################################
41. #  注意, 然而, 如果将变量中包含一个注释的代码块将会引发问题
42. #  例如:

45. #/!/bin/bash

47. : <<COMMENTBLOCK
48. echo "This line will not echo."
49. &*@!!++=
50. ${foo_bar_bazz?}
51. $(rm -rf /tmp/foobar/)
52. $(touch my_build_directory/cups/Makefile)
53. COMMENTBLOCK

56. $ sh commented-bad.sh
57. commented-bad.sh: line 3: foo_bar_bazz: parameter null or not set

59. # 有效的补救办法就是在 49 行的位置加上单引号,变为 'COMMENTBLOCK'.

61. : <<'COMMENTBLOCK'

63. # 感谢 Kurt Pfeifle 指出这一点.
  • 另一个漂亮的方法使得”自文档化”的脚本成为可能

样例 19-12. 自文档化的脚本

1. #!/bin/bash
2. # self-document.sh: self-documenting script
3. # Modification of "colm.sh".

5. DOC_REQUEST=70

7. if [ "$1" = "-h"  -o "$1" = "--help" ]     # 请求帮助.
8. then
9. echo; echo "Usage: $0 [directory-name]"; echo
10. sed --silent -e '/DOCUMENTATIONXX$/,/^DOCUMENTATIONXX$/p' "$0" |
11. sed -e '/DOCUMENTATIONXX$/d'; exit $DOC_REQUEST; fi

14. : <<DOCUMENTATIONXX
15. List the statistics of a specified directory in tabular format.
16. ---------------------------------------------------------------
17. The command-line parameter gives the directory to be listed.
18. If no directory specified or directory specified cannot be read,
19. then list the current working directory.

21. DOCUMENTATIONXX

23. if [ -z "$1" -o ! -r "$1" ]
24. then
25. directory=.
26. else
27. directory="$1"
28. fi

30. echo "Listing of "$directory":"; echo
31. (printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \
32. ; ls -l "$directory" | sed 1d) | column -t

34. exit 0

使用 cat script 是另一种可行的方法.

1. DOC_REQUEST=70

3. if [ "$1" = "-h"  -o "$1" = "--help" ]     # Request help.
4. then                                       # Use a "cat script" . . .
5. cat <<DOCUMENTATIONXX
6. List the statistics of a specified directory in tabular format.
7. ---------------------------------------------------------------
8. The command-line parameter gives the directory to be listed.
9. If no directory specified or directory specified cannot be read,
10. then list the current working directory.

12. DOCUMENTATIONXX
13. exit $DOC_REQUEST
14. fi

另请参阅 样例 A-28, 样例 A-40, 样例 A-41, and 样例 A-42 更多样例请阅读脚本附带的注释文档.

  • 嵌入文档创建了临时文件, 但这些文件在打开且不可被其他程序访问后删除.
1. bash$ bash -c 'lsof -a -p $$ -d0' << EOF
2. > EOF
3. lsof    1213 bozo    0r   REG    3,5    0 30386 /tmp/t1213-0-sh (deleted)
  • 某些工具在嵌入文档内部并不能正常运行.
  • 在嵌入文档的最后关闭限定符必须在起始的第一个字符的位置开始.行首不能是空格. 限制符后尾随空格同样会导致意想不到的行为.空格可以防止限制符被当做其他用途. [1]
1. #!/bin/bash

3. echo "----------------------------------------------------------------------"

5. cat <<LimitString
6. echo "This is line 1 of the message inside the here document."
7. echo "This is line 2 of the message inside the here document."
8. echo "This is the final line of the message inside the here document."
9. LimitString
10. #^^^^限制符的缩进. 出错! 这个脚本将不会如期运行.

12. echo "----------------------------------------------------------------------"

14. #  这些评论在嵌入文档范围外并不能输出

16. echo "Outside the here document."

18. exit 0

20. echo "This line had better not echo."  # 紧跟着个 'exit' 命令.
  • 有些人非常聪明的使用了一个单引号(!)做为限制符. 但这并不是个好主意
1. # 这个可以运行.
2. cat <<!
3. Hello!
4. ! Three more exclamations !!!
5. !

8. # 但是 . . .
9. cat <<!
10. Hello!
11. Single exclamation point follows!
12. !
13. !
14. # Crashes with an error message.

17. # 然而, 下面这样也能运行.
18. cat <<EOF
19. Hello!
20. Single exclamation point follows!
21. !
22. EOF
23. # 使用多字符限制符更为安全.

为嵌入文档设置这些任务有些复杂, 可以考虑使用 expect, 一种专门用来和程序进行交互的脚本语言。

Notes:   除此之外, Dennis Benzinger 指出, 使用 <<- 抑制 tab.