我們知道平常在linux
命令行的操作都可以放到文件裏面,賦予可執行權限後,就可以將這文件變成一個shell
腳本。但是如果我們跟有些程序交互時,shell
腳本卻幫不了我們太多。比如編輯一個文件和操作數據庫。編輯一個文件一般用vi
,進去後hjkl
的aio
的操作什麼的,腳本怎麼執行?mysql
登陸輸入mysql -u 用戶 -p
密碼後,就跟mysql
進行一串交互,shell
怎麼執行?Here Document
就可以派上用場了。
什麼是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.sh
echo "hello"
echo "world"
EOF
使用 sh here.sh
運行這個腳本文件,會得到output.sh
這個新文件,裏面的內容如下
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
的時候可以將內容部分進行縮進,方便閱讀代碼。
Here Document的兩個應用
- shell編輯文件。
shell
編輯文件最常用的方法就是echo 字符串 >> 文件
。但是要刪除一行怎麼辦?Here Document
就搞定了。在Here Document
中使用vi是不行的。替代方法是使用ed
命令。在命令行執行以下:
$ touch base.txt
$ ed base.txt
a
this is line1.
this is line2.
this is line3.
this is line4.
.
wq
先新建一個文件base.txt
,然後ed
這個文件,輸入a
表示最後追加,輸入了四行文字。.
表示結束輸入。wq
表示保存退出。
那我們再用ed
命令,在shell
腳本里面對這個文件再次進行操作。如下。
#!/bin/sh
ed base.txt << !ED1_JEREMIAH!
3
d
i
this is line 3 new.
.
w
q
!ED1_JEREMIAH!
解釋下:ed base.txt << !ED1_JEREMIAH!
表示編輯base.txt
,用變量!ED1_JEREMIAH!
標記,這裏搞的變量複雜爲了和shell
中的其他變量進行區分。3
表示到第3
行,d
表示刪除,然後i
表示本行增加,輸入this is line 3 new
。其他的同上述。最後用!ED1_JEREMIAH!
結束。也就是說兩個!ED1_JEREMIAH!
之間的每一行都是類似與命令行輸入到ed
名中,進行交互。
執行的結果如下所示。
$ sh ed_file.sh && cat base.txt
60
this is line3.
65
this is line1.
this is line2.
this is line 3 new.
this is line4.
關於ed
的操作和參數,可以查看linux
幫助或去搜索相關的資料。
- shell控制數據庫
假設執行下面的操作訪問數據庫。
$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1257
Server version: 5.1.35-community MySQL Community Server (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
mysql> select * from user;
mysql> exit
Bye
如果我們要用shell
腳本訪問,則可以編寫如下的腳本。
#!/bin/sh
mysql -u root << !ED2_JEREMIAH!
use mysql
select * from user;
exit
!ED2_JEREMIAH!
執行如下。
sh mysql_access.sh