Last Updated: February 25, 2016
·
1.971K
· lukemadhanga

Run a remote backup and then a local restore using this small shell script

So you have a remote server and a development machine (obviously, how do you test your new code). Your remote server has a lot of user input so to test your code against current data you write a script to backup your data server side. The only problem is that you have to constantly SSH and SCP to get your data. Wouldn't it be great if you could do all of this with one command?

# remotebackupandlocalrestore

echo '######## Download and Back Up Bachtrack Database ########'

# Connect to the server and run a few functions
# Running commands on remote server from local machine http://goo.gl/7VhjSp

ssh me@mydomain.com << EOF

# Remove remote sql files from previous backups

rm -v mybackup.sql

# Run the backup script

mybackupscript

exit
EOF

echo '######## Attempting to remove existing backups on the local machine ########'

# Search and remove any sql files from previous backups

rm -v mybackup.sql

# Download the backup from the server, putting it in the current directory

scp me@mydomain.com:mybackup.sql .

# Restore the database

echo '######## Enter MySQL Password For My DataBase ########'
mysql -uroot -p mydatabasename < mybackup.sql

If you don't have a backup script, replace mybackupscript with

mysqldump -uroot -p mydatabasename > mybackup.sql

If you don't accept SSH connections over port 20, change ssh me@mydomain.com and scp me@mydomain.com:mybackup.sql . with

ssh -p1234 me@mydomain.com
scp -P1234 me@mydomain.com:mybackup.sql .

where 1234 is the port which you accept SSH connections on your remote server

Add the script to your PATH so that to run it, all you have to do is

remotebackupandlocalrestore

Alternatively, you could run the script absolutely by doing

/path/to/remotebackupandlocalrestore