转载自: http://my.oschina.net/u/1032146/blog/146941linux
什么是Here Document?
Here Document 是在Linux Shell 中的一种特殊的重定向方式,它的基本的形式以下
cmd << delimiter
Here Document Content
delimiter
其做用是将两个 delimiter 之间的内容(Here Document Content 部分) 传递给cmd 做为输入参数;
好比在终端中输入cat << EOF,系统会提示继续进行输入,输入多行信息再输入EOF,中间输入的信息将会显示在屏幕上;以下:
fish@mangos:~$ cat << EOF
> First Line
> Second Line
> Third Line EOF
> EOF
First Line
Second Line
Third Line EOF
注:'>'这个符号是终端产生的提示输入信息的标识符
这里要注意几点:
EOF只是一个标识而已,能够替换成任意的合法字符(约定大于配置);
做为结尾的delimiter必定要顶格写,前面不能有任何字符;
做为结尾的delimiter后面也不能有任何的字符(包括空格!!!);
做为起始的delimiter先后的空格会被省略掉;
Here Document 不只能够在终端上使用,在shell 文件中也能够使用,例以下面的here.sh 文件
cat << EOF > output.txt
echo "hello"
echo "world"
EOF
使用 sh here.sh 运行这个脚本文件,会获得output.txt 这个新文件,其内容以下:
echo "hello"
echo "world"
Here Document的变形
delimiter 与变量
在Here Document 的内容中,不只能够包括普通的字符,还能够在里面使用变量;
例如将上面的here.sh 改成
cat << EOF > output.sh
echo "This is output"
echo $1
EOF
使用sh here.sh HereDocument 运行脚本获得output.sh的内容
echo "This is output"
echo HereDocument
在这里 $1 被展开成为了脚本的参数 HereDocument
可是有时候不想展开这个变量怎么办呢,能够经过在起始的 delimiter的先后添加 " 来实现,例如将上面的here.sh 改成
cat << "EOF" > output.sh #注意引号
echo "This is output"
echo $1
EOF
获得的output.sh 的内容为
echo "This is output"
echo $1
<< 变为 <<-
Here Document 还有一个用法就是将 '<<' 变为 '<<-'
使用 <<- 的惟一变化就是Here Document 的内容部分每行前面的tab(制表符)将会被删除掉;
该用法在编写Here Document时可将内容部分进行缩进,方便阅读代码.shell