Here document
Here document (here-document, here-text, heredoc, hereis, here-string, here-script)是一个文件文字或输入流文字:它是源代码文件的一部分,被视为它是一个单独的文件。该术语还用于使用类似语法,保留换行符和文本中的其他空格(包括缩进)的多行字符串文字形式。
简单的说here document将内容I/O重定向到交互程序或终端,在编写脚本时十分方便。
在Unix Shell中使用Here document
使用示例
命令 << EOF //EOF作为定界符可以是任何字符串,结束时要使用对应的字符进行结束
...
EOF //这里结束符前面不能有空格、缩进,大小写也要保持一致
当需要输入一大段内容到某个文件,使用echo输入一段大内容就显得太麻烦了。
echo "one" > outfile.txt
echo "two" >> outfile.txt
echo -e "three\nfour" >> outfile.txt
Here document可以更加简单明了的进行同样的操作。
cat << EOF > outfile.txt
one
two
three
four
EOF
Here document与交互程序进行操作
mysql -u root << SQL
exit
SQL
忽略缩进
在“<<”后面加上“-”符号可以忽略缩进
cat <<- EOF
one
two
three
EOF
输出结果:
one
two
three
对比不加“-”符号输出结果:
cat << EOF
one
two
three
EOF
输出结果:
one
two
three
使用’EOF’、”EOF”或`EOF`
当定界符被任何引号括住,将不会对内容进行处理。
示例:
xyz=Hello
cat << EOF
`date`
$xyz
EOF
输出结果:
2017年 7月20日 星期四 12时28分55秒 CST
Hello
当我们不希望,”$xyz”和”`date`”被处理时,又不希望使用”\”进行字符转义 影响可读性,
可以使用引号将定界符括住。
xyz=Hello
cat << 'EOF'
`date`
$xyz
EOF
输出结果:
`date`
$xyz
xyz=Hello
cat << "EOF"
`date`
$xyz
EOF
输出结果:
`date`
$xyz
还可以使用反引号,不过结束时也要带上 ` 符号
xyz=Hello
cat << `EOF`
`date`
$xyz
`EOF`
输出结果:
`date`
$xyz
在PHP中使用Here document
例如:
<?php
your_name = "Cola";
echo <<<EOF
hello, $your_name!
test
EOF;
hi = <<<EOF
Hello,world!
EOF;
echo $hi;
?>
输出:
hello,Cloa!
test
Hello,world!