Linux Shell Here Document

Here Document 是一种有特殊用处的代码块,他使用IO重定向的形式记录了一段临时的文本或交互命令,并且把这些文本或命令 依次的传递给一个程序或一个命令,作为他运行时的标准输入。

Here document的语法格式为

void@void-ThinkPad-E450:~/linuxShellArg$ command << delimiter
> document
> docuemnt
> document
> delimiter

bash把操作符<<看成输入指令,后面的delimiter是标识符开始和结束的标识符,bash会一直输出提示符>,用来等待用户输入数据,一直到用户输入第二个delimiter标识符为止,他表明输入结束。两个delimiter之间的数据都会作为command命令的标准输入。

标识符delimiter可以使用任意字符串,但是delimiter只能是一个词,中间不能有空格或Tab键。

Here document 经常o用在Shell脚本的帮助函数中,例如android的build/envsetup.sh

function hmm() {
cat <<EOF
Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
- lunch:   lunch <product_name>-<build_variant>
- tapas:   tapas [<App1> <App2> ...] [arm|x86|mips|armv5] [eng|userdebug|user]
- croot:   Changes directory to the top of the tree.
- m:       Makes from the top of the tree.
- mm:      Builds all of the modules in the current directory, but not their dependencies.
- mmm:     Builds all of the modules in the supplied directories, but not their dependencies.
- mma:     Builds all of the modules in the current directory, and their dependencies.
- mmma:    Builds all of the modules in the supplied directories, and their dependencies.
- cgrep:   Greps on all local C/C++ files.
- jgrep:   Greps on all local Java files.
- resgrep: Greps on all local res/*.xml files.
- godir:   Go to the directory containing a file.

Look at the source to view more functions. The complete list is:
EOF
    T=$(gettop)
    local A
    A=""
    for i in `cat $T/build/envsetup.sh | sed -n "/^function /s/function \([a-z_]*\).*/\1/p" | sort`; do
      A="$A $i"
    done
    echo  $A
}

在函数hmm()中通过here document显示了一些帮助信息,这里通过cat命令 把here document输出到屏幕上,且delimiter标识符使用了EOF。

上一篇:3、Node.js使用模板引擎简单介绍


下一篇:linux系统和android系统的区别