Linux Shell Here Document

Here Document 是一種有特殊用處的代碼塊,他使用IO重定向的形式記錄了一段臨時的文本或交互命令,而且把這些文本或命令 依次的傳遞給一個程序或一個命令,做爲他運行時的標準輸入。linux

Here document的語法格式爲android

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

bash把操做符<<當作輸入指令,後面的delimiter是標識符開始和結束的標識符,bash會一直輸出提示符>,用來等待用戶輸入數據,一直到用戶輸入第二個delimiter標識符爲止,他代表輸入結束。兩個delimiter之間的數據都會做爲command命令的標準輸入。shell

標識符delimiter能夠使用任意字符串,可是delimiter只能是一個詞,中間不能有空格或Tab鍵。bash

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。ui

相關文章
相關標籤/搜索