Here Document

http://jeremiah.blog.51cto.com/539865/339211

Here Document是已“<< 变量”为标识的一段Shell程序
  
    这里就写Here Document的两个应用。
 
    1. shell编辑文件。
     shell编辑文件最常用的方法就是echo 字符串 >> 文件。但是要删除一行怎么办?Here Document就搞定了。
    经Jeremiah测试,在Here Document中使用vi是不行的。替代方法是使用ed命令。在命令行执行以下:
$ touch base.txt 
$ ed base.txt 

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! 



this is line 3 new. 



!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帮助或去搜索相关的资料。
 
    2. 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
    可以看到结果相同。
    在网上还看到过可以将查询的结果放置到Shell的变量中,这种高级操作大家有兴趣的自己去Google吧。
posted @ 2014-03-18 10:02  義丨往昔灬miller  阅读(289)  评论(0)    收藏  举报