Code stuff about Bash on Aug 27, 2008 Write comment

Bash script to empty a mysql database

I wrote a bash shell script that deletes all the tables in a mysql database and I thought I’d just post it here in case anyone might find it useful. It accepts one required argument which is the database name and one optional argument which is the username with DROP/CREATE DATABASE privileges to dbname .

#!/bin/bash
if [[ ${1} == '' ]]
then
echo “”
echo ” `basename ${0}` {dbname} [{user}]”
echo “”
echo ” {dbname} – is the name of the mysql database to zap”
echo ” {user} – optional, user ‘root’ is used as default”
echo “”
exit 1;
else
read -p “Are you sure you want to empty ${1} [Y/N]? ” ans
if [[ ${ans} == "y" || ${ans} == "Y" ]]
then
user=${2:-”root”}
echo -n “Using mysql user ‘${user}’, ”
mysql -u ${user} -p -e “drop database ${1};create database ${1};” && echo “${1} emptied.”
exit 0;
else
echo “Aborted.”
exit 1;
fi
fi

Note: Oh and be careful in using the script ‘coz it will erase all the data in your database so make sure you have backups. ;-)