您的位置:首页 > 运维架构 > Shell

【BASH】如何避免Here-Document的奇怪行为

2009-04-14 14:51 211 查看
【BASH】如何避免Here-Document的奇怪行为

如果不了解Here-Document,请看bash
man page中here-documents的部分,也可以看本文后面附录的在man
page 中截取的here-document说明。

如果您的Here-Document行为怪诞,比如您维护捐赠者的名单,并且创建了如下面这样的donor文件:

$ cat donors
#
# simple
lookup of our generous donors

#
grep $1 <<EOF
# name amt
pete $100
joe $200
sam $ 25
bill $ 9
EOF
$
但是当您如果用下面的方式调用,那么会得到如下的奇怪输出
$ ./donors
bill

pete bill00
bill $ 9
$ ./donors
pete

pete pete00
$

解决方法
关掉shell脚本的一个功能:在Here-Document中忽略ending
marker前的任何字符
# solution
grep $1 <</EOF
pete $100
joe $200
sam $ 25
bill $ 9
EOF

讨论:
实际上使用<</EOF
<<'EOF',甚至<<E/OF都可以达到这样的效果,但是<</EOF在语法上面更加的简洁。

通常的情况(除非向上面solution给出的方式),bash的
manpage中这样说明“在here-documents中的行都服从于参数扩展,命令替换,和数学表达式扩展

这样就比较清晰了,$100在./donor
bill的用例中将被视为$1和两个零,这样就等于是bill00

一个建议是除非你明确的想使用命令扩展,参数扩展等功能,还是使用<<'EOF'或者<</EOF这样的方式避免一些bash的怪异行为(看起来的怪异行为)

here-documents

The format of here-documents is:

<<[-]word

here-document
delimiter

No parameter
expansion, command substitution, arithmetic expansion, or

pathname expansion is performed on word. If any characters in word
are
quoted, the delimiter is the result of quote removal on
word, and the
lines in the here-document are not
expanded. If word is unquoted, all
lines of the
here-document are subjected to parameter expansion, com-

mand substitution, and arithmetic expansion. In the latter case,
the
character sequence /<newline> is ignored, and /
must be used to quote
the characters /, $, and `.

If the redirection operator is <<-, then all leading tab
characters are
stripped from input lines and the line
containing delimiter. This
allows here-documents within
shell scripts to be indented in a natural
fashion.

如果英文看不太清楚呢,可以参考下面的这个网页 http://linux.tnc.edu.tw/techdoc/perl_intro/x338.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: