Skip to content

Instantly share code, notes, and snippets.

@GiovanniK
Last active January 3, 2023 15:50
Show Gist options
  • Save GiovanniK/b018edac377e663dd4d3d5fd4f157fff to your computer and use it in GitHub Desktop.
Save GiovanniK/b018edac377e663dd4d3d5fd4f157fff to your computer and use it in GitHub Desktop.
Linux backup script (local + ftp + sftp)
#!/bin/bash
archiveLocation=/backups
archiveTempPath=/backups/tmp_backup
archiveName=$(date '+%d-%m-%Y_%H:%M');
archiveFullName=$archiveName.tar.gz
archivePath=$archiveLocation/$archiveFullName
deleteLocalArchive=false
backupPath=/var/www
backupToRemoteServer=false
remoteServerProtocol=sftp
remoteServerPort=22
remoteServerHost=
remoteServerUsername=
remoteServerPassword=
remoteServerPath=/
backupMysql=false
backupMysqlUsername=
backupMysqlPassword=
backupMysqlDatabase=
# Create temporary folder
echo 'Creating temporary folders';
mkdir $archiveTempPath
mkdir $archiveTempPath/files
mkdir $archiveTempPath/databases
# Set permissions
echo 'Setting file permissions';
chmod -R 777 $archiveTempPath
# Copy all the files
echo 'Copying all files to temporary location';
rsync -a $backupPath $archiveTempPath/files -q
# Export MySQL database
if [ $backupMysql = true ]
then
echo "Exporting database: $backupMysqlDatabase";
mysqldump -u$backupMysqlUsername -p$backupMysqlPassword $backupMysqlDatabase > $archiveTempPath/databases/$backupMysqlDatabase.sql 2>&1
fi
# Tar all files
cd $archiveTempPath
tar -I pigz -cf "$archivePath" *
cd $archiveLocation
# Upload archive to external server
if [ $backupToRemoteServer = true ]
then
echo "Uploading archive ($remoteServerProtocol)";
if [ $remoteServerProtocol = 'ftp' ]
then
curl -T $archivePath ftp://$remoteServerHost:$remoteServerPort/$remoteServerPath/ --user $remoteServerUsername:$remoteServerPassword -s
elif [ $remoteServerProtocol == 'sftp' ]
then
sshpass -p $remoteServerPassword scp -P $remoteServerPort $archivePath $remoteServerUsername@$remoteServerHost:$remoteServerPath/$archiveFullname
fi
fi
# Remove all the temporary files
echo 'Removing temporary files';
rm -rf $archiveTempPath
# Remove local archive if necessary
if [ $deleteLocalArchive = true ]
then
echo 'Removing local archive';
rm -rf $archivePath;
fi
# Done!
echo "Backup $archiveFullName was completed";
@GiovanniK
Copy link
Author

GiovanniK commented May 16, 2018

SFTP requires sshpass (apt install sshpass)
Compression requires pigz (apt install pigz)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment