一个方便的数据库操作shell脚本
用法说明
这个脚本可以方便的备份和恢复数据库,而且通过show参数可以用来查看该实例中有多少个数据库。
唯一需要手动操作的是到脚本里配置账号密码。账号密码放在脚本的目的是为了避免每次输入。
导出文件格式是tar.gz。导入的文件格式是zip。这部分跟我的习惯有关系,我备份的数据库都会在本地进行处理压缩成zip上传,就是为了防止没有经过处理的数据库直接拿去导入。
#!/bin/bash
# 这是一个自动化导出MySQL数据库的脚本
# 修改此处
user="root"
passwd="123456"
port=3306
host="127.0.0.1"
dblist=(
"test"
)
root=`pwd`"/"
function printUsage {
echo "Usage:"
echo "$0 [-t dump|import|show] [-f file]"
echo "导出/导入数据库脚本 v1.1"
echo "导出的sql以数据库命名。"
echo "导入的文件同样是提取sql文件名!"
echo "show 参数可以打印数据库名,用于替换dblist"
echo "dump文件是tar.gz的压缩包,import的文件是zip的压缩包"
}
function printParaErr {
echo "参数错误!"
}
function printFileNotExist {
echo "文件不存在!"
}
function printFileNotSupport {
echo "仅支持压缩文件!(zip)"
}
function cleanOutDir {
if [ -d $outDir ]; then
echo "清理临时目录:" $outDir
rm -rf $outDir
fi
}
function addNote {
echo "是否添加备注文件?[回车跳过]"
read note
if [ ${#note} -gt 1 ];then
cd $root$outDir
echo $note > note.txt
fi
}
if [ $# == 0 ]; then
printUsage
exit 0
fi
GETOPTOUT=`getopt t:f: "$@"`
set -- $GETOPTOUT
while [ -n "$1" ]
do
case $1 in
-t)
type=$2
shift
;;
-f)
inputfile=$2
shift
;;
--)
shift
break
;;
*)
printParaErr
printUsage;
exit 1;
;;
esac
shift
done
if [ $type == 'dump' ]; then
echo "目标数据库为 $user@$host:$port"
elif [ $type == 'import' ]; then
if [ ! -f "$inputfile" ]; then
printFileNotExist
printUsage
exit 0
fi
ext_name="${inputfile##*.}"
if [ $ext_name != 'zip' ]; then
printFileNotSupport
printUsage
exit 0
fi
echo "导入源数据为: $inputfile"
echo "目标数据库为: $user@$host:$port"
elif [ $type == 'show' ]; then
echo "当前实例存在的数据库:(已排除系统数据库)"
else
printParaErr
printUsage;
exit 1;
fi
# echo "请输入数据库密码,按回车键结束"
# stty -echo # 设置输入字符不回显
# read passwd
# stty echo # 取消不回显状态
runTime=`date '+%Y%m%d%H%M'`
outDir="./sqlHandler_$runTime/"
cleanOutDir
if [ $type == 'dump' ]; then
echo "创建导出目录:" $outDir
mkdir -p $outDir
for db_name in ${dblist[*]}; do
cmd="mysqldump -h $host -u $user -P $port -p$passwd $db_name"
echo $cmd | sed "s/-p$passwd/-p****/g";
$cmd > "$outDir$db_name.sql";
done
cd $outDir
tar cvzf "dbbak_$runTime.tar.gz" *
rm -rf *.sql
addNote
echo "导出文件为:"
echo $root$outDir"/"`ls|grep tar`|sed -e "s/\/\//\//g" -e "s/\/\.\//\//g"
elif [ $type == 'import' ]; then
echo "创建临时目录:" $outDir
mkdir -p $outDir
unzip -d $outDir $inputfile
files=$(ls $outDir)
cd $outDir
echo "mysql command:"
for file in ${files[*]}; do
db_name="${file%.*}"
# ext_name="${file##*.}"
cmd="mysql -h $host -u $user -P $port -p$passwd --default-character-set=utf8 $db_name"
echo -e "\t"$cmd " < $file" | sed "s/-p$passwd/-p****/g";
$cmd < $file
done
cd $root
cleanOutDir
# $cmd < $inputfile
elif [ $type == 'show' ]; then
rm -rf $outDir
cmd="mysql -h $host -u $user -P $port -p$passwd "
$cmd -e "show databases;" |grep -v -E 'Database|mysql|information_schema|performance_schema'|sed -e 's/^/"/g' -e 's/$/"/g'
# echo $result
fi
if [[ $? == 0 ]]; then
echo "操作完成!";
else
echo "┗━━ 操作失败!";
fi
