将mysqldump文件从一个目录复制到备份目录

时间:2014-11-17 14:26:52

标签: mysql linux shell crontab

我正在构建一个shell脚本,它将在crontab的帮助下每晚运行,我的脚本会一直轰炸并向我发出错误"语法错误:单词意外(预期" do&#34 )。

脚本本身为它在目录中找到的每个MySQL文件创建一个新目录,然后将文件从相应的mysqldump目录复制到创建的目录。如果我使用此代码在正确的轨道上,请告诉我以及可能导致我的文件结束错误的原因。我是shell脚本的新手,会接受任何建议。如果有更好的方法来编写我的代码,那么也可以在这方面提供帮助。

CDPATH="/backups/mysql"
#
now=$(date +"%Y_%m_%d")
#
# Find Directory Name
#
for file in */; do
    dir=${file%/}
    if [[ -e "$dir"]]
    then
        echo "Directory Exists!"
    else
        echo "Directory doesn't exist."
    fi
done
#
# Copy MySQL Databases
#
while [ -d $dir ]; do                                      # Check existing Dirs
    cp -upf /dbase/files/*.sql /backups/mysql/$dir/$now    # If Dir exists, create copy
    if [ ! -d $dir ]; then                                 # If Dir nonexistant create
        mkdir -p $dir
        cp -upf /dbase/files/*.sql /backups/mysql/$dir/$now
    else                                                   # If all else fails just create a copy in /mysql
        cp -upf /dbase/files/*.sql /backups/mysql/$dir/$now
    fi
done

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

 1.请勿在“其他”之后使用“then”  2.第二行可能不是你想要的。它只是将变量dir设置为字符串“dir(/ backups / mysql / *)”
......问题已经改变,已经过时了。

我假设,文件格式如下......
/dbase/files/db1.sql
/dbase/files/db2.sql ...

...应备份到以下目的地:

/backups/mysql/db1/2014_11_18/db1.sql

#!/bin/bash
BACKUP_DIR="/backups/mysql/"
FILE_DIR=/dbase/files/
now=$(date +"%Y_%m_%d")

# setting the input field seperator to newline
IFS=$'\n'

# find db backups and loop over
for file in $(find ${FILE_DIR} -maxdepth 1 -name "*.sql" -type f -exec basename {} \;); do
    # create backup directory:
    mkdir -p "${BACKUP_DIR}${file%.sql}/${now}"

    # copy file over        
    cp "${FILE_DIR}${file}" "${BACKUP_DIR}${file%.sql}/${now}/"
done

将脚本转换为unix编码:

dos2unix script.sh
相关问题