Skip to content

Instantly share code, notes, and snippets.



Last active May 6, 2016
What would you like to do?
MySQL backup using Ruby script

MySQL backup using Ruby script

This is a simple script that I wrote to backup my local databases. It uses terminal-notifier to create OS notifications and time_difference to report how much time it takes to execute a backup.


  • Install the required gems: gem install time_difference terminal-notifier
  • Adjust the relevant variables: databases, path
  • The connection variables are set in the .my.cnf file. I don't want your MySQL password in the script.
    • Create the following .my.cnf file in your home directory. The correct permission for this file is 600:
  • Run the script: ruby backup.rb

Extra tip: you should create an user with only select privilegies to execute this backup script

require 'terminal-notifier'
require 'time_difference'
started_at =
databases = %w(database1 database2 database3)
path = '/Users/youruser/backups'
start_message = 'Backup started'
puts start_message
TerminalNotifier.notify(start_message, title: 'MySQL Backup')
databases.each do |database|
filename = "#{path}/#{database}_#{"%Y%m%d%H%M")}.sql"
cmd = "mysqldump #{database} > #{filename}"
puts "Database: #{database}"
finished_at =
puts "Deleting old backups..."
system("find #{path} -type f -mtime +3 -delete")
end_message = "Backup ended in #{TimeDifference.between(started_at, finished_at).in_seconds} seconds"
puts end_message
TerminalNotifier.notify(end_message, title: "MySQL Backup")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment