shel中的Here Document

目錄

什麼是Here Document

Here Document的變形

delimiter 與變量

« 變爲 «-

參考鏈接


什麼是Here Document

Here Document 是在Linux Shell 中的一種特殊的重定向方式,它的基本的形式如下

cmd << delimiter

Here Document Content

delimiter

它的作用就是將兩個 delimiter 之間的內容(Here Document Content 部分) 傳遞給cmd 作爲輸入參數。

比如在終端中輸入cat << EOF ,系統會提示繼續進行輸入,輸入多行信息再輸入EOF,中間輸入的信息將會顯示在屏幕上。如下:

$ cat << EOF

> First Line

> Second Line

> Third Line 

> EOF

First Line

Second Line

Third Line 

注: >這個符號是終端產生的提示輸入信息的標識符

這裏要注意幾點

  1. EOF 只是一個標識而已,可以替換成任意的合法字符
  2. 作爲結尾的delimiter一定要頂格寫,前面不能有任何字符
  3. 作爲結尾的delimiter後面也不能有任何的字符(包括空格)
  4. 作爲起始的delimiter前後的空格會被省略掉

Here Document 不僅可以在終端上使用,在shell 文件中也可以使用,例如下面的here.sh 文件

  1. cat << EOF > output.sh

  2. echo "hello"

  3. echo "world"

  4. EOF

使用 sh here.sh 運行這個腳本文件,會得到output.sh 這個新文件,裏面的內容如下

  1. echo "hello"

  2. echo "world"

Here Document的變形

delimiter 與變量

在Here Document 的內容中,不僅可以包括普通的字符,還可以在裏面使用變量,例如將上面的here.sh 改爲

  1. cat << EOF > output.sh

  2. echo "This is output"

  3. echo $1

  4. EOF

使用sh here.sh HereDocument 運行腳本得到output.sh的內容

  1. echo "This is output"

  2. echo HereDocument

在這裏 $1 被展開成爲了腳本的參數 HereDocument

但是有時候不想展開這個變量怎麼辦呢,可以通過在起始的 delimiter的前後添加 " 來實現,例如將上面的here.sh 改爲

  1. cat << "EOF" > output.sh #注意引號

  2. echo "hello"

  3. echo "world"

  4. EOF

得到的output.sh 的內容爲

  1. echo "This is output"

  2. echo $1

« 變爲 «-

Here Document 還有一個用法就是將 '«' 變爲 '«-'。 使用 <<- 的唯一變化就是Here Document 的內容部分每行前面的 tab (製表符)將會被刪除掉,這種用法是爲了編寫Here Document的時候可以將內容部分進行縮進,方便閱讀代碼。

參考鏈接

Wiki: Here Document
Learn Linux, 101: Streams, pipes, and redirects

【轉自:http://my.oschina.net/u/1032146/blog/146941】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章