Dump MySQL / MariaDB databases with one file per table

linux
mysql
Published

January 26, 2020

I often use mysqldump to export databases with MySQL or MariaDB. But mysqldump has no option to dump a full database and write each table dump in a separate file, so I wrote a little bash script for that.

Here it is :

#!/bin/bash
########################################################################
# This script dumps a MySQL/MariaDB database in a folder, each table in
# a separate file.
# USE IT AT YOUR OWN RISK, IT COMES WITH NO WARRANTY AT ALL.
# Getopts part inspired by http://tuxtweaks.com/2014/05/bash-getopts/
########################################################################

#Set Script Name variable
SCRIPT=`basename ${BASH_SOURCE[0]}`

function HELP {
  echo -e \\n"This script dumps a MySQl database in a folder, each table in a separate file."\\n
  echo -e "${REV}Basic usage:${NORM} ${BOLD}$SCRIPT -d database${NORM}"\\n
  echo "Other command line switches are optional. The following switches are recognized."
  echo "${REV}-f${NORM}  -- Output folder. Default is ${BOLD}./${NORM}."
  echo "${REV}-u${NORM}  -- MySQL username."
  echo "${REV}-p${NORM}  -- MySQL password."
  echo -e "${REV}-s${NORM}  -- Add \"USE `database`;\" statement in each file."\\n
  echo -e "(c) François Perruchas, 2016"\\n
  exit 0
}

NUMARGS=$#
if [ $NUMARGS -eq 0 ]; then
  HELP
fi

while getopts :d:f:u:p:sh FLAG; do
  case $FLAG in
    d)  
      database=$OPTARG
      ;;
    f)  
      dest=$OPTARG
      ;;
    u)
      mysqluser=$OPTARG
      ;;
    p)  
      mysqlpwd=$OPTARG
      ;;
    s)  
      statement="yes"
      ;;
    h)  #show help
      HELP
      ;;
    \?) #unrecognized option - show help
      echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
      HELP
      ;;
  esac
done

if [ "$database" == "" ]; then
    echo "Database parameter missing"
    HELP
fi

if [ "$dest" == "" ]; then
    dest="./"
fi
echo "Database to export : $database"
echo "Destination folder : $dest"
read -p "If this is correct, press [Enter] to continue or Ctrl + C to exit..."

# Getting MySQL Connexion info
if [ "$mysqluser" == "" ]; then
  read -p "MySQL user: " mysqluser
  echo ""
fi
if [ "$mysqlpwd" == "" ]; then
  read -s -p "MySQL password: " mysqlpwd
  echo ""
fi
echo ""
# Getting tablelist
tablelist=$(echo "USE $database; SHOW TABLES" | mysql -u$mysqluser -p$mysqlpwd | tail -n +2)

if [ "$tablelist" == "" ]; then
    echo "Database unknown or empty !!!"
    exit
else
  # Creating destination folder if it doesn't exist
  if [ ! -d "$dest" ]; then
    echo "Creating destination directory because it doesn't exist"
    mkdir -p $dest
  fi
  export IFS=$'\n';
  for t in $tablelist
  do
    echo "Exporting table: $t"
    if [ "$statement" == "yes" ]; then
      echo "USE $database;" > "$dest/$t.sql"
    fi
    mysqldump -u$mysqluser -p$mysqlpwd --add-drop-table "$database" "$t" >> "$dest/$t.sql"
  done
fi