Page 80 of 170

Backup (mysql dump) all your MySQL databases in separate files

Sometimes we would like to dump all the MySQL databases. MySQL provides an easy solution to this problem:

mysqldump -u root -p --all-databases > all_dbs.sql

However this will dump stuff into one file. How to dump all databses into separate files? Well, here is my solution. A small bash script:

#! /bin/bash

TIMESTAMP=$(date +"%F")
BACKUP_DIR="/backup/$TIMESTAMP"
MYSQL_USER="backup"
MYSQL=/usr/bin/mysql
MYSQL_PASSWORD="password"
MYSQLDUMP=/usr/bin/mysqldump

mkdir -p "$BACKUP_DIR/mysql"

databases=`$MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)"`

for db in $databases; do
  $MYSQLDUMP --force --opt --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db | gzip > "$BACKUP_DIR/mysql/$db.gz"
done

Be aware, that in order to execute this script from cron, you need to store password in it (so cron won't be prompted to provide a password). That's why, you should not use a root account. Instead just create a new user only for backups, with following privileges:

  • SHOW DATABASES
  • SELECT
  • LOCK TABLES
  • RELOAD
  • SHOW VIEW

Qnap – Adding items to cron permanently

Quick hint on how to add a permanent task in Qnap cron (one that will be there after reboot or update).

Login to your Qnap via ssh and edit the crontab with:

vim /etc/config/crontab

And after that just run:

crontab /etc/config/crontab
/etc/init.d/crond.sh restart

And that's all. One more thing that is worth mentioning, is that you should not put your sripts in /root directory. Unless you want to do some magic with your Qnap, you will loose all the scripts after reboot. So probably the best idea is not to put your scripts in /root dir.

Copyright © 2025 Closer to Code

Theme by Anders NorenUp ↑