1. 程式人生 > 其它 >linux tee和cat使用EOF往檔案中新增內容

linux tee和cat使用EOF往檔案中新增內容

EOF和 -EOF區別

後者會自動刪除tab產生的空格

1、覆蓋

這裡有兩種格式可以使用

格式一

#!/bin/bash
cat << EOF > /root/test.txt
Hello!
My site is www.361way.com
My site is www.91it.org
Test for cat and EOF!
EOF

格式二

#!/bin/bash
cat > /root/test.txt <<EOF
Hello!
My site is www.361way.com
My site is www.91it.org
Test for cat and EOF!
EOF

兩種寫法區別無法是要寫入的檔案放在中間或最後的問題,至於選哪種看個人喜好吧。

2、追加

覆蓋的寫法基本和追加一樣,不同的是單重定向號變成雙重定向號。

格式一

#!/bin/bash
cat << EOF >> /root/test.txt
Hello!
My site is www.361way.com
My site is www.91it.org
Test for cat and EOF!
EOF

格式二

#!/bin/bash
cat >> /root/test.txt <<EOF
Hello!
My site is www.361way.com
My site is www.91it.org
Test for cat and EOF!
EOF

需要注意的是,不論是覆蓋還是追加,在涉及到變數操作時是需要進行轉義的,例如:

#!/bin/bash
cat <<EOF >> /root/a.txt
PATH=\$PATH:\$HOME/bin
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=\$ORACLE_BASE/10.2.0/db_1
export ORACLE_SID=yqpt
export PATH=\$PATH:\$ORACLE_HOME/bin
export NLS_LANG="AMERICAN_AMERICA.AL32UTF8"
EOF

語法

tee [-ai][--help][--version][檔案...]

引數:

-a或--append  附加到既有檔案的後面,而非覆蓋它.
-i或--ignore-interrupts  忽略中斷訊號。
--help  線上幫助。
--version  顯示版本資訊。

例項
使用指令"tee"將使用者輸入的資料同時儲存到檔案"file1"和"file2"中,輸入如下命令:

$ tee file1 file2 #在兩個檔案中複製內容

以上命令執行後,將提示使用者輸入需要儲存到檔案的資料,如下所示:

My Linux #提示使用者輸入資料
My Linux #輸出資料,進行輸出反饋

此時,可以分別開啟檔案"file1"和"file2",檢視其內容是否均是"My Linux"即可判斷指令"tee"是否執行成功。