Skip to content

Instantly share code, notes, and snippets.

@shoaibi
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save shoaibi/ec5ecc7b82cdc13a1766 to your computer and use it in GitHub Desktop.

Select an option

Save shoaibi/ec5ecc7b82cdc13a1766 to your computer and use it in GitHub Desktop.
Drop or truncate tables in a mysql database
#!/bin/bash
MDB="$1"
KEYWORD="$2"
# Detect paths
MYSQL=$(which mysql)
AWK=$(which awk)
GREP=$(which grep)
E_BADARGS=65
if [ $# -ne 2 ]
then
echo "Usage: $0 {MySQL-Database-Name} {DROP|TRUNCATE}"
echo "Drops/Truncates all tables from a MySQL"
exit $E_BADARGS
fi
# make sure we can connect to server
$MYSQL -e "use $MDB" &>/dev/null
if [ $? -ne 0 ]
then
echo "Error - Cannot connect to mysql server using given username, password or database does not exits!"
exit 2
fi
TABLES=$($MYSQL $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
# make sure tables exits
if [ "$TABLES" == "" ]
then
echo "Error - No table found in $MDB database!"
exit 3
fi
QUERY="SET FOREIGN_KEY_CHECKS = 0;";
for t in $TABLES
do
QUERY="${QUERY}${KEYWORD} table $t;"
done
QUERY="${QUERY}SET FOREIGN_KEY_CHECKS = 1;"
$MYSQL $MDB -e "${QUERY}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment