##什么是Here Document## Here Document 是在Linux Shell 中的一种特殊的重定向方式,它的基本的形式以下shell
cmd << delimiter Here Document Content delimiter
它的做用就是将两个 delimiter 之间的内容(Here Document Content 部分) 传递给cmd 做为输入参数。code
好比在终端中输入cat << EOF
,系统会提示继续进行输入,输入多行信息再输入EOF,中间输入的信息将会显示在屏幕上。以下:ip
fish@mangos:~$ cat << EOF > First Line > Second Line > Third Line EOF > EOF First Line Second Line Third Line EOF
注: >
这个符号是终端产生的提示输入信息的标识符get
这里要注意几点cmd
Here Document 不只能够在终端上使用,在shell 文件中也能够使用,例以下面的here.sh 文件it
cat << EOF > output.sh echo "hello" echo "world" EOF
使用 sh here.sh
运行这个脚本文件,会获得output.sh 这个新文件,里面的内容以下pip
echo "hello" echo "world"
###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
im
可是有时候不想展开这个变量怎么办呢,能够经过在起始的 delimiter的先后添加 "
来实现,例如将上面的here.sh 改成
cat << "EOF" > output.sh #注意引号 echo "hello" echo "world" EOF
获得的output.sh 的内容为
echo "This is output" echo $1
###<< 变为 <<-### Here Document 还有一个用法就是将 '<<' 变为 '<<-'。 使用 <<-
的惟一变化就是Here Document 的内容部分每行前面的 tab (制表符)将会被删除掉,这种用法是为了编写Here Document的时候能够将内容部分进行缩进,方便阅读代码。
##参考连接## Wiki: Here Document<br /> Learn Linux, 101: Streams, pipes, and redirects