Skip to content

Instantly share code, notes, and snippets.

@mocanuga
Created April 26, 2017 10:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mocanuga/eff26a3dcc40ef657a1c812f68511f6d to your computer and use it in GitHub Desktop.
Save mocanuga/eff26a3dcc40ef657a1c812f68511f6d to your computer and use it in GitHub Desktop.
Truncate all tables in a mysql or mariadb database shell script
#! /bin/bash
############################################
# don't forget to chmod +x reset_database #
# usage: ./reset_database dbname #
# enter db password when prompted #
############################################
# set the database name
DATABASE_NAME=$1
# get the db user from the keyboard
read -p "DB User: " DBUSER
#get the db password from the keyboard
read -s -p "DB Password: " DBPASSWORD
# just to move to the next line
echo ""
# truncate all the tables in one go
mysql -Nse 'show tables' -D $DATABASE_NAME -u$DBUSER -p$DBPASSWORD | while read table; do echo "SET FOREIGN_KEY_CHECKS = 0;truncate table \`$table\`;SET FOREIGN_KEY_CHECKS = 1;"; done | mysql $DATABASE_NAME -u$DBUSER -p$DBPASSWORD
exit 0
Copy link

ghost commented Aug 17, 2018

where should i write these commands

@mithlajkn
Copy link

I tried this on different DBs. but its showing ERROR 1146 (42S02) at line 402: Table 'dbname.inventory_stock_1' doesn't exist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment