您的位置:首页 > 运维架构 > Shell

Shell之Here Document

2014-04-17 16:44 267 查看
EOF本意是 End Of File,表明到了文件末尾。

使用格式基本是这样的:
命令 << EOF
内容段
EOF
将“内容段”整个作为命令的输入。
你的代码里就是用cat命令读入整段字符串并赋值给list变量。
其实,不一定要用EOF,只要是“内容段”中没有出现的字符串,都可以用来替代EOF,只是一个起始和结束的标志罢了。

有个特殊用法不得不说:
: << COMMENTBLOCK
shell脚本代码段
COMMENTBLOCK
这个用来注释整段脚本代码。 : 是shell中的空语句。

例一:使用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 <<EOF
use mysql
select * from user;
exit
EOF


例二:使用shell为数据库用户授权

cat > /tmp/mysql_sec_script<<EOF
use mysql;
update user set password=password('$mysqlrootpwd') where user='root';
delete from user where not (user='root') ;
delete from user where user='root' and password='';
drop database test;
DROP USER ''@'%';
flush privileges;
EOF

/usr/local/mysql/bin/mysql -u root -p$mysqlrootpwd -h localhost < /tmp/mysql_sec_script

rm -f /tmp/mysql_sec_script


cat命令详解

用法:cat [选项]... [文件]...
将[文件]或标准输入组合输出到标准输出。

-A, --show-all 等于-vET
-b, --number-nonblank 对非空输出行编号
-e 等于-vE
-E, --show-ends 在每行结束处显示"$"
-n, --number 对输出的所有行编号
-s, --squeeze-blank 不输出多行空行
-t 与-vT 等价
-T, --show-tabs 将跳格字符显示为^I
-u (被忽略)
-v, --show-nonprinting 使用^ 和M- 引用,除了LFD和 TAB 之外
--help 显示此帮助信息并退出
--version 显示版本信息并退出

如果没有指定文件,或者文件为"-",则从标准输入读取。

示例:
cat f - g 先输出f 的内容,然后输出标准输入的内容,最后输出g 的内容。
cat 将标准输入的内容复制到标准输出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: