Glam Prestige Journal

Bright entertainment trends with youth appeal.

Given:

Directory tree that contains files with .sql extension.

Requred

Find them all recursively and pass found files one by one to mysql client as:

mysql < ./dir/subdir/subsubdir/schema.sql

My feeble attempt

find . -name '*.sql' | xargs mysql

Results in:

ERROR 1049 (42000): Unknown database './dir/subdir/subsubdir/schema.sql'

Question

How to do it right?

Thanks!

2 Answers

I believe this will work

find . -type f -name '*.sql' -exec bash -c 'cat '{}' | mysql' \;

Basically the above finds all files ending in .sql (I put the -type f in there just in case there are any directories that end in .sql). For each file found, find runs the exec command. The exec runs a bash sub-shell that cats the file and pipes that to the mysql program.

Hope this helps.

2

In stead of trying to execute everything, consider going a two step route: collect all paths to files into single file, then use source command to run the resulting file

find . type f -name '*.sql' -printf 'source %P;\n' > allsql.txt
mysql -u <user> -p -e "source allsql.txt"

Of course, if different sql files reference different databases or have conflicting queries - mysql will throw errors, and therefore even though this may work, this is generally not the best idea. You also should keep in mind that a database name for which you run queries should be provided on command line or via statement use <databasename>.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy