linux shell的here document用法(cat EOF)
什么是Here Document?
Here Document 是在Linux Shell 中的一種特殊的重定向方式,它的基本的形式如下
cmd << delimiter
? Here Document Content
delimiter
其作用是將兩個 delimiter 之間的內容(Here Document Content 部分) 傳遞給cmd 作為輸入參數;
比如在終端中輸入cat << EOF,系統會提示繼續進行輸入,輸入多行信息再輸入EOF,中間輸入的信息將會顯示在屏幕上;如下:
fish@mangos:~$ 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時可將內容部分進行縮進,方便閱讀代碼.
?
轉自:https://blog.csdn.net/wangjunjun2008/article/details/24351045
轉載于:https://www.cnblogs.com/poissonnotes/p/9041737.html
總結
以上是生活随笔為你收集整理的linux shell的here document用法(cat EOF)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle根据年份分组
- 下一篇: 牛客SQL题解 - 查找employee