Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to truncate all MySql tables

I'm looking for a Unix shell script that will truncate all tables in a schema. A similar question was already asked, but I have some additional requirements which makes none of the provided answers satisfactory:

  • Must be a Unix shell script (i.e. no python, perl, PHP)
  • The script must truncate the tables in an order which respects foreign key constraints
  • I'd prefer not to have to use a stored proc

Thanks in advance, Don

like image 672
Dónal Avatar asked May 20 '26 12:05

Dónal


1 Answers

How about something cheeky like this:

mysqldump  --no-data mydb | mysql mydb

Gets a dump of the schema and replays it into the database!

Alternatively, check out mk-find in Maatkit, you should be able to do something like this:

mk-find -exec "truncate %s"

Description of mk-find:

This tool is the MySQL counterpart to the UNIX ‘find’ command. It accepts tests (such as “find all tables larger than 1GB”) and performs actions, such as executing SQL (”DROP TABLE %s”). With this tool at your disposal you can automate many tedious tasks, such as measuring the size of your tables and indexes and saving the data for historical trending, dropping old scratch tables, and much more. It is especially useful in periodic scheduled tasks such as cron jobs.

like image 127
Paul Dixon Avatar answered May 23 '26 04:05

Paul Dixon