Shell备份数据库脚本编写

数据库备份

#!/bin/bash 
# Mysql data 目录
db_data_dir=/alidata/server/mysql/data
# Mysql bin 目录
db_bin_dir=/alidata/server/mysql/bin
# Mysql 备份目录
db_backup_dir=/root/db_back

# Mysql 用户名
username=root
# Mysql 密码
password="19940921"
# Mysql host
host=localhost

# Mysql 数据库名字
db_names=()

today=`date +%Y-%m-%d`

files=(`ls "${db_data_dir}"`)
for file in ${files[*]}
do
    test -d ${db_data_dir}/${file}
    if [ $? -eq 0 ]
        then
            db_names+=("${file}")
    fi  
done

for dbname in ${db_names[*]}
do
    test -e ${db_backup_dir}/${dbname}
    if [ $? -ne 0 ]
        then
            echo "${dbname} 备份文件夹建立"
            mkdir -p ${db_backup_dir}/${dbname}
            chmod -R 777 ${db_backup_dir}/${dbname}
    fi
    echo "${dbname} 备份开始"
    ${db_bin_dir}/mysqldump -u${root} -p${password} -h${host} ${dbname} > ${db_backup_dir}/${dbname}/${today}.sql
    chmod a+x ${db_backup_dir}/${dbname}/*
done

数据库恢复

#!/bin/bash 
test $# -ne 2 -o ! -f $1
if [ $? -eq 0 ]
        then
                echo "脚本参数不符"
        exit
fi

# Mysql data 目录
db_data_dir=/alidata/server/mysql/data
# Mysql bin 目录
db_bin_dir=/alidata/server/mysql/bin

# Mysql 用户名
username=root
# Mysql 密码
password="19940921"
# Mysql host
host=localhost

# Mysql 数据库名字

files=(`ls "${db_data_dir}"`)
flag=0
for file in ${files[*]}
do
    test -d ${db_data_dir}/${file} -a ${file} = $2
    if [ $? -eq 0 ]
        then
            flag=1
            break
    fi  
done

if [ ${flag} -eq 0 ]
    then
        echo "$2 数据库不存在"
        exit
fi

${db_bin_dir}/mysqldump -u${root} -p${password} -h${host} $2 < $1
echo "$2 已经恢复" 


你可能感兴趣的:(shell)