# Shell Here Document ## Here Documents基本用法 Here Document是一种特殊的代码块, 通常作为一种I/O重定向的方式给命令提供输入 格式如下: ``` COMMAND < one two three > uno ods tres > EOF ONE TWO THREE UNO ODS TRES ``` 例2:非交互式地使用vim 模拟sed的用法,在输入文件中插入两行文本 ``` #/bin/sh # Noninteractive use of 'vi' to edit a file. # Emulates 'sed'. E_BADARGS=85 if [ -z "$1" ] then echo "Usage: `basename $0` filename" exit $E_BADARGS fi TARGETFILE=$1 # Insert 2 lines in file, then save. #--------Begin here document-----------# vim $TARGETFILE <. # Bram Moolenaar points out that this may not work with 'vim' #+ because of possible problems with terminal interaction. exit ``` 例3:非交互式地使用ex 将所有txt文件中的Smith替换为Jones ``` # Replace all instances of "Smith" with "Jones" #+ in files with a ".txt" filename suffix. ORIGINAL=Smith REPLACEMENT=Jones for file in $(fgrep -l $ORIGINAL *.txt) do # ------------------------------------- ex $file < $filename << End-of-message` 那么cat将会把输出写入文件中,而不会输出到标准输出 ## 忽略前导的tab符号 格式如下: ``` COMMAND <<-delimiter ... ... ... delimiter ``` 例: ``` #!/bin/sh cat <<-ENDOFMESSAGE This is line 1 of the message. This is line 2 of the message. This is line 3 of the message. This is line 4 of the message. This is the last line of the message. ENDOFMESSAGE exit 0 ``` delimiter以 `-` 开头, 将会去除行首的tab符号,但不包括空格符号 注意: 对非行首的tab符号无效 ## 禁止变量替换 默认情况下, HereDocuments支持变量替换 例1: ``` cat << EOF current dir=${PWD} EOF 命令输出结果如下: current dir=/data/repo/blog ``` 可以通过对delimiter的任何部分添加引号标签,取消变量替换 例2: ``` cat << "EOF" current dir=${PWD} EOF 命令输出结果如下: current dir=${PWD} ``` 例3: ``` cat << "E"OF current dir=${PWD} EOF 命令输出结果如下: current dir=${PWD} ``` ## 多行注释 使用Anonymous Here Documents对代码块进行多行注释 格式如下: ``` : <