how to write a bash script which will dump 开发者_StackOverflowa database and restore it. there should be two arguments. first one is the name of db which is going to be dumped and another one is name of the db in which i am going to restore the previously dump data.
I got a python script who take the dump and upload it to s3. I think its better than bash script:
import datetime
import subprocess, tarfile, os, S3, tempfile
#Mysql
MYSQL_USER = "xxxx"
MYSQL_PASS = "xxx"
MYSQL_DB = "xxxxx"
MYSQL_HOST = "localhost"
MYSQL_DUMP = "mysqldump"
AWS_ACCESS_KEY_ID = "xxxxxxxxxxxx"
AWS_SECRET_ACCESS_KEY = "yyyyyyyyyyyyyyyyyyyy"
BUCKET_NAME = "bucket"
FOLDER = "backup/"
KEEP = 5
EXT_TIME = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%H:%M')
print "start mysqldump..."
proc1 = subprocess.Popen(MYSQL_DUMP + " --no-create-info -u %s -p%s -x --databases %s" % (MYSQL_USER, MYSQL_PASS, MYSQL_DB), shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
t1 = tempfile.NamedTemporaryFile()
t1.write(proc1.communicate()[0])
tar = tarfile.open( (os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % (EXT_TIME))), "w|gz")
tar.add(t1.name, MYSQL_DB + "_data.sql")
t1.close()
tar.close()
print "uploading to S3..."
conn = S3.AWSAuthConnection( AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY )
tardata = open(os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % EXT_TIME) , "rb").read()
response = conn.put(BUCKET_NAME, FOLDER + MYSQL_DB + "_%s.tar.gz" % EXT_TIME, S3.S3Object(tardata))
if response.http_response.status == 200 :
print "sucessfully uploaded the archive to Amazon S3"
else:
print "Uploading database dump to Amazon S3 is not successful"
os.remove(os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % (EXT_TIME)))
Try this:
#!/bin/bash
mysqldump $1 > test.sql
mysql $2 -uusername -ppassword < test.sql
rm test.sql
May be you'll need any optional arguments to mysqldump and mysql commands
精彩评论