由于之前一客户服务器异常导致innodb表数据文件损,加innodb_force_recovery参数后,不能使用mysqldump备份(未开启binlog);隧想到用select into outfile来导出相关数据.
但是select into outfile一次只能操作一张表,对于一个有三百多张表的数据库来就,如果一个表一个表地select,简直是一场噩梦!!!
于是便有了下面的脚本,以mysql数据库为例:
点击(此处)折叠或打开
#!/bin/bash
#FileName:select_into_bak.sh
#Desc:Use select into outfile to backup db or tables
#Created By:fedoracle
#Date:2012/04/24
DB=mysql
USER=test
PASSWD=test
HOST=192.168.164.129
BAK_DIR=/data/mysql/backup/$DB
DATE=`date "+%Y-%m-%d %H-%M-%S"`
[ -d "$BAK_DIR" ] || /bin/mkdir -p $BAK_DIR && /bin/chown mysql:mysql $BAK_DIR
/usr/local/mysql/bin/mysql -h$HOST -u$USER -p$PASSWD -e "show tables from $DB" | grep -v "Tables_in" > $BAK_DIR/tables.txt
for table in `cat $BAK_DIR/tables.txt`
do
/usr/local/mysql/bin/mysql -h$HOST -u$USER -p$PASSWD -e "select * from $DB.$table into outfile '"$BAK_DIR/$table".txt' character set utf8;"
done
cd $BAK_DIR
/bin/tar -czf "$DB-$DATE".tar.gz *.txt
/bin/rm -f *.txt
exit 0
以下为测试结果:
点击(此处)折叠或打开
[root@MySql01 scripts]# sh select_into_bak.sh
[root@MySql01 scripts]# ll /data/mysql/backup/mysql
total 128
-rw-r--r-- 1 root root 125779 Apr 24 16:15 mysql-2012-04-24 16-15-30.tar.gz
[root@MySql01 scripts]# tar -tvf /data/mysql/backup/mysql/mysql-2012-04-24\ 16-15-30.tar.gz
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:30 columns_priv.txt
-rw-rw-rw- mysql/mysql 152 2012-04-24 16:15:30 db.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:30 event.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:30 func.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:30 general_log.txt
-rw-rw-rw- mysql/mysql 2 2012-04-24 16:15:30 global_trans_id.txt
-rw-rw-rw- mysql/mysql 915 2012-04-24 16:15:30 help_category.txt
-rw-rw-rw- mysql/mysql 5605 2012-04-24 16:15:30 help_keyword.txt
-rw-rw-rw- mysql/mysql 7488 2012-04-24 16:15:30 help_relation.txt
-rw-rw-rw- mysql/mysql 429714 2012-04-24 16:15:30 help_topic.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 host.txt
-rw-rw-rw- mysql/mysql 6 2012-04-24 16:15:31 last_exec_tran.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 ndb_binlog_index.txt
-rw-rw-rw- mysql/mysql 40 2012-04-24 16:15:31 plugin.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 procs_priv.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 proc.txt
-rw-rw-rw- mysql/mysql 78 2012-04-24 16:15:31 proxies_priv.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 servers.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 slow_log.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 tables_priv.txt
-rw-r--r-- root/root 308 2012-04-24 16:15:30 tables.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 time_zone_leap_second.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 time_zone_name.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 time_zone_transition.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 time_zone_transition_type.txt
-rw-rw-rw- mysql/mysql 0 2012-04-24 16:15:31 time_zone.txt
-rw-rw-rw- mysql/mysql 1288 2012-04-24 16:15:31 user.txt
--转自