A robust Bash script to create compressed backups of a MySQL database while excluding high-churn, non-essential tables. This is specifically optimized for Laravel applications to avoid backing up massive log tables (Telescope, Activity Log, Sessions, etc.).
- Smart Exclusions: Automatically ignores data from tables that bloat backups but aren't critical for restoration (e.g.,
telescope_entries,sessions,failed_jobs,audit_logs). - Compression: Pipes output directly to
gzipto save disk space. - Safety:
- Automatically creates the backup directory if it doesn't exist.
- Uses
MYSQL_PWDenvironment variable to avoid "using password on command line" security warnings.
- Maintainable: Uses a Bash array for the exclusion list, making it easy to add or remove tables without fighting complex string concatenation.
Download the backup.sh file to your server.
Open the file and update the top configuration section with your database credentials:
DB_USER="forge"
DB_PASS="your_secure_password"
DB_HOST="localhost"
DB_NAME="your_database_name"
BACKUP_DIR="database/backup"You can also add or remove tables from the EXCLUDED_TABLES array to suit your needs.
Make the script executable and run it using Bash:
chmod +x backup.sh
./backup.shNote: Do not run with
sh backup.sh. This script uses Bash arrays, which are not supported by the defaultshshell on Ubuntu/Debian.
To run this backup daily at 2:00 AM, add the following to your crontab (crontab -e):
0 2 * * * /path/to/your/backup.sh > /dev/null 2>&1By default, the script ignores the table that generally don't want to backup (in context of a Laravel Application):
- Session/Auth:
sessions,password_reset_tokens,personal_access_tokens - Queue:
jobs,failed_jobs - Logs & Monitoring:
telescope_entries,telescope_entries_tags,telescope_monitoring,activity_log,audit_logs - Cache:
cache