最近在生产环境写了个备份数据库的脚本,大致备份原理是,在数据库中查出所有业务数据库名称,再用mysqldump对查到的数据库名称进行备份。测试时完全没问题,但第二天却发现备份失败了
检查日志,发现报错为数据库名不存在,于是检查了数据库名查询的相关脚本
#select all schema name of mysql into file schema_name.txt
mysql -uroot -p'passwd' --socket=/var/lib/mysql/mysql.sock -e "select schema_name from information_schema.schemata where schema_name not in ('mysql','information_schema','performance_schema','sys')" | awk 'NR>1' > /root/mysqldump/scripts/schema_name.txt
执行上面的脚本后
cat /root/mysqldump/scripts/schema_name.txt
商贸 备份 20190717
atom_interface
db_bs
db_bs_2019-07-12
db_crm
db_hr
db_pms
db_pms_03-19
db_seed
db_tms
db_wms
oms_ui
原因在于开发人员新建的数据库库名中出现了空格(测试脚本时没有出现库名含空格的库,并且一般来说,虽说Mysql是允许的,但这样的库名是很不规范的,因此没有考虑到),因此需要对查询出的库名进行处理,用双引号括("XXX")起来,使用mysql -e执行SQL时也是需要用双引号将语句括起来,因此需要对SQL语句中的双引号进行转义,后来发现转义的关键字为反斜杠"\",最终将脚本改写为:
#select all schema name of mysql into file schema_name.txt
mysql -uroot -p'passwd' --socket=/var/lib/mysql/mysql.sock -e "select concat('\"',schema_name,'\"') from information_schema.schemata where schema_name not in ('mysql','information_schema','performance_schema','sys')" | awk 'NR>1' > /root/mysqldump/scripts/schema_name.txt
执行脚本后
cat /root/mysqldump/scripts/schema_name.txt
“商贸 备份 20190717“
"atom_interface"
"db_bs"
"db_bs_2019-07-12"
"db_crm"
"db_hr"
"db_pms"
"db_pms_03-19"
"db_seed"
"db_tms"
"db_wms"
"oms_ui"
问题成功解决