#!/bin/sh
stty -echo
printf 'Password: ' >&2
read PASSWORD
stty echo
printf "\n"
if [ -z "$PASSWORD" ]; then
echo 'No password given!'
exit 1
fi
MYSQL_CONN="-uroot -p$PASSWORD"
mysql ${MYSQL_CONN} --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM mysql.user WHERE user<>''" | mysql ${MYSQL_CONN} --skip-column-names -A | sed 's/$/;/g'
#!/bin/bash
# This script will backup all mysql databases into
# compressed file named after date, ie: /var/backup/mysql/2016-07-13.tar.bz2
# Setup variables used later
# Create date suffix with "F"ull date format
suffix=$(date +%F)
# Retrieve all database names except information schemas. Use sudo here to skip root password.
dbs=$(sudo mysql --defaults-extra-file=/root/.my.cnf --batch --skip-column-names -e "SHOW DATABASES;" | grep -E -v "(information|performance)_schema")
# Create temporary directory with "-d" option
tmp=$(mktemp -d)
# Set output dir here. /var/backups/ is used by system,
# so intentionally used /var/backup/ for user backups.
outDir="/var/backup/mysql"
# Create output file name
out="$outDir/$suffix.tar.bz2"
# Actual script
# Check if output directory exists
if [ ! -d "$outDir" ];then
# Create directory with parent ("-p" option) directories
sudo mkdir -p "$outDir"
fi
# Loop through all databases
for db in $dbs; do
# Dump database to temporary directory with file name same as database name + sql suffix
sudo mysqldump --defaults-extra-file=/root/.my.cnf --databases "$db" > "$tmp/$db.sql"
done
# Go to tmp dir
cd $tmp
# Compress all dumps with bz2, discard any output to /dev/null
sudo tar -jcf "$out" * > "/dev/null"
# Cleanup
cd "/tmp/"
sudo rm -rf "$tmp"