1. 程式人生 > >linux shell的here document用法

linux shell的here document用法

什麽是 編寫 標識符 通過 nbsp fis 傳遞 腳本 不能

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


什麽是Here Document?
Here Document 是在Linux Shell 中的一種特殊的重定向方式,它的基本的形式如下
cmd << delimiter
Here Document Content
delimiter

其作用是將兩個 delimiter 之間的內容(Here Document Content 部分) 傳遞給cmd 作為輸入參數;
比如在終端中輸入cat << EOF,系統會提示繼續進行輸入,輸入多行信息再輸入EOF,中間輸入的信息將會顯示在屏幕上;如下:
[email protected]:~$ cat << EOF

> First Line
> Second Line
> Third Line EOF
> EOF
First Line
Second Line
Third Line EOF
註:‘>‘這個符號是終端產生的提示輸入信息的標識符

這裏要註意幾點:
EOF只是一個標識而已,可以替換成任意的合法字符(約定大於配置);
作為結尾的delimiter一定要頂格寫,前面不能有任何字符;
作為結尾的delimiter後面也不能有任何的字符(包括空格!!!);
作為起始的delimiter前後的空格會被省略掉;


Here Document 不僅可以在終端上使用,在shell 文件中也可以使用,例如下面的here.sh 文件
cat << EOF > output.txt
echo "hello"
echo "world"
EOF

使用 sh here.sh 運行這個腳本文件,會得到output.txt 這個新文件,其內容如下:
echo "hello"
echo "world"

Here Document的變形

delimiter 與變量

在Here Document 的內容中,不僅可以包括普通的字符,還可以在裏面使用變量;
例如將上面的here.sh 改為
cat << EOF > output.sh
echo "This is output"
echo $1
EOF
使用sh here.sh HereDocument 運行腳本得到output.sh的內容

echo "This is output"
echo HereDocument
在這裏 $1 被展開成為了腳本的參數 HereDocument

但是有時候不想展開這個變量怎麽辦呢,可以通過在起始的 delimiter的前後添加 " 來實現,例如將上面的here.sh 改為
cat << "EOF" > output.sh #註意引號
echo "This is output"
echo $1
EOF

得到的output.sh 的內容為
echo "This is output"
echo $1

<< 變為 <<-

Here Document 還有一個用法就是將 ‘<<‘ 變為 ‘<<-‘
使用 <<- 的唯一變化就是Here Document 的內容部分每行前面的tab(制表符)將會被刪除掉;
該用法在編寫Here Document時可將內容部分進行縮進,方便閱讀代碼.

linux shell的here document用法