Bash Script: Easily Backup your Magento2 Code Files + Database

We had created a similar Backup Script for Magento1 in the past. Now we are back with the much-improvised version for Magento2.
You must be wondering why we needed a bash script for Magento2 backup even it comes up with inbuilt console command:

php /path/to/magento2/bin/magento setup:backup -v --code --media --db

Some of the reasons are:

  • Linux native command is always faster than PHP.
  • There is no enabling and disabling of maintenance mode while running the backup script. So there is no downtime.
  • To have more Freedom. Magento2 console script is limited. What if you want to backup in Amazon S3, Google Drive, etc.? If you have an independent script you can play as you like without worrying about breaking the Magento2 system.

You can find the full script below:

Please visit our GitHub project page for more info: MagePsycho/magento2-db-code-backup-bash-script

Installation

You can simply download the script file and give the executable permission.
In a Linux system this can be simply done as:

cd /path/to/your/preferred/download/folder
curl -O mage2-backup.sh https://raw.githubusercontent.com/MagePsycho/magento2-db-code-backup-bash-script/master/src/mage2-db-code-backup.sh
chmod +x mage2-backup.sh

If you want to make this command system-wide then

sudo mv mage2-backup.sh /usr/local/bin/mage2-backup.sh

Usage

To display help

./mage2-backup.sh --help

mage2-backup-script-help

To backup database only


./mage2-backup.sh --type=db --src-dir=/path/to/magento2/root --dest-dir=/path/to/destination

To backup code only


./mage2-backup.sh --type=code --skip-media=1 --src-dir=/path/to/magento2/root --dest-dir=/path/to/destination

To backup code + database


./mage2-backup.sh --type=all --skip-media=1 --src-dir=/path/to/magento2/root --dest-dir=/path/to/destination

To schedule backup via Cron
You can run this command manually (on demand) or via cron.
If you want to schedule via Cron, just add the following line in your Crontab entry (crontab -e)


0 0 * * * /path/to/mage2-backup.sh --type=all --skip-media=1 --src-dir=/path/to/magento2/root --dest-dir=/path/to/destination > /dev/null 2>&1

0 0 * * * expression means the command will run at every midnight. You can refer to https://crontab.guru/ to know more about the cron-expression.

Hope you will find this script useful in your day-to-day operation. Any issues found can be raised at our GitHub project – Bash Script: Backup Magento2 Code + Database

Let us know your experience/feedback on this script.