Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MySQL DB backup script in Ruby CMD
#1===========First code================
#!/usr/bin/env ruby
databases = {
:local_db => {
:database => 'my_db',
:username => 'root',
:password => 'admin',
:host => 'localhost'
},
:staging_db => {
:database => 'db_name',
:username => 'db_user',
:password => 'p@ssWord!',
:host => 'localhost'
}
}
end_of_iter = ARGV.shift
databases.each do |name, config|
if end_of_iter.nil?
backup_file = config[:database] + '_' + Time.now.strftime('%Y%m%d')
else
backup_file = config[:database] + '_' + end_of_iter
end
mysqldump = "mysqldump -h#{config[:host]} -u#{config[:username]} -p#{config[:password]} #{config[:database]}"
`#{mysqldump} > #{backup_file}.sql`
`gzip #{backup_file}.sql`
end
#2===========Taking database info from the command line instead of an internal Hash================
#!/usr/bin/env ruby
database = ARGV.shift
username = ARGV.shift
password = ARGV.shift
host = ARGV.shift
end_of_iter = ARGV.shift
if end_of_iter.nil?
backup_file = database + '_' + Time.now.strftime('%Y%m%d')
else
backup_file = database + '_' + end_of_iter
end
mysqldump = "mysqldump -h#{host} -u#{username} -p#{password} #{database}"
`#{mysqldump} > #{backup_file}.sql`
`gzip #{backup_file}.sql`
# To perform our backup, we call it like so: db_backup.rb db_name username password host_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.