here文檔? here doc EOF重定向
http://www.cnblogs.com/xiangzi888/archive/2012/03/24/2415077.html
?
在shell腳本程序中,向一條命令傳遞輸入的一種特殊方法是使用here文檔。一個here document就是一段帶有特殊目的的代碼段。它使用I/O重定向的形式將一個命令序列傳遞到一個交互程序或者命令中。它允許一條命令在獲得輸入數據時就好像是在讀取一個文件或鍵盤一樣,而實際是從腳本程序中得到輸入數據。格式:
COMMAND <<SpecialString
...
SpecialString
SpecialString用來界定命令序列的范圍,是一個特殊的字符序列,用來界定命令序列的范圍,可自定義,但不能出現在傳遞命令的文檔內容中。
使用舉例:
1.使用cat打印多行消息,也可重定向哦(echo 有點麻煩了),同樣支持參數替換哦
cat <<EOF > /tmp/test this is here doc! date $HOME EOF this is here doc! date /home/xiangzi888
?
#重寫 cat > /tmp/a.txt<< EOF [client] port = $port socket = /data/mysql/mysql$port/tmp/mysql.sock [mysqld_safe] #malloc-lib= /usr/local/mysql/lib/mysql/libjemalloc.so EOF#追加 cat >> /tmp/a.txt<< EOF [client] port = $port socket = /data/mysql/mysql$port/tmp/mysql.sock [mysqld_safe] #malloc-lib= /usr/local/mysql/lib/mysql/libjemalloc.so EOF
?
2.設置變量
var=$(cat <<EOF content EOF )
?
3. 廣播: 將消息發送給每個登陸的用戶
wall <<HALT E-mail your noontime orders for pizza to the system administrator. # more messages # 注意: 'wall'命令會把注釋行也打印出來. HALT
?
4.帶有抑制tab功能的多行消息(去掉每行前面的TAB字符)
cat <<-EOF this is here doc! date doesn't work EOF
?
5.關閉變量替換的功能 ?
cat <<'EOF' $HOME doesn't work here! EOF
?
?
6.生成另外一個腳本(比較詭異!)
(cat <<'EOF' #!/bin/bash # Note that since we are inside a subshell, #+ we can't access variables in the "outside" script. echo "Generated file will be named: /tmp/script.sh" # Instead, the result is literal output. a=7 b=3 c=$(($a * $b)) echo "c = $c" exit 0 EOF ) > /tmp/script.sh
?
7.here doc與函數
#!/bin/bash #這個函數看起來就是一個交互函數, 但是... GetPersonalData () {read firstnameread lastnameread address }# 給上邊的函數提供輸入. GetPersonalData <<DATA Robert Bozeman Hust DATA
?
?
8.‘匿名’here文檔,不顯示!(利用 : 可以注釋掉一段代碼塊,或者寫一個自文檔化(self-documenting)的腳本,詳見:http://www.tsnc.edu.cn/default/tsnc_wgrj/doc/abs-3.9.1_cn/html/here-docs.html)
#!/bin/bash # 如果其中某個變量沒被設置, 那么就打印錯誤信息. : <<TESTVARIABLES ${HOSTNAME?}${USER?}${MAIL?} TESTVARIABLESexit 0
?
?
9.一些注意事項
a.某些工具是不能放入here document中運行的。
b.結尾的limit string, 就是here document最后一行的limit string, 必須從第一個字符開始. 它的前面不能夠有任何前置的空白. 而在這個limit string后邊的空白也會引起異常. 空白將會阻止limit string的識別.
c.對于那些使用"here document", 并且非常復雜的任務, 最好考慮使用expect腳本語言, 這種語言就是為了達到向交互程序添加輸入的目的而量身定做的.
?
?
?
?
f