Created
October 14, 2010 21:52
-
-
Save coreyward/627135 to your computer and use it in GitHub Desktop.
Ruby wrapper to `mysqldump`. Intended to make setting up automatic cronjob backups easier by avoiding bash scripting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Usage: | |
| ruby mysql_backup.rb db:name [user:your_username] \ | |
| [password:your_password] \ | |
| [host:your_hostname] \ | |
| [file:output_file.sql] | |
| Feel free to use, improve, etc. I'm new to Ruby, so excuse anything that makes your palm slap your forehead. ;) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Automatically backup a MySQL database | |
| require 'date' | |
| option = {} | |
| begin | |
| ARGV.each do |arg| | |
| param, value = arg.split ':' | |
| raise "Invalid argument: '#{arg}'" unless option[param.to_sym] = value | |
| end | |
| # Make sure the database was specified | |
| raise "Missing required argument '#{db}'." if option[:db].nil? | |
| rescue Exception => e | |
| puts e.message | |
| exit | |
| end | |
| # Setup the file | |
| option[:file] ||= option[:db] + '_' + DateTime.now.strftime("%Y%m%d%H%M%S") + '.sql' | |
| unless option[:path].nil? | |
| option[:path] += '/' unless option[:path] =~ /\/$/ | |
| option[:file] = option[:path] + option[:file] | |
| end | |
| # Assemble the mysqldump command | |
| cmd = ["mysqldump"] | |
| { :u => :user, :p => :password, :h => :host }.each do |p,v| | |
| cmd << "-#{p}#{option[v]}" unless option[v].nil? | |
| end | |
| cmd << option[:db] | |
| cmd << "> #{option[:file]}" | |
| cmd = cmd.join " " | |
| # Call it | |
| puts `#{cmd}` ? "Successfully backed up #{option[:db]}." : "Failed. See #{option[:file]} for details." | |
| # gzip the data if desired | |
| puts `gzip #{option[:file]}` unless option[:gzip].nil? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment