1

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 2

1

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
  • Thanks! Would this: 1) pipe contents of .sql files into mysql client; or 2) launch shell command mysql ./schema.sql ?
    – temuri
    Nov 13, 2018 at 14:23
  • 1
    Yes. For example, if you have a file called schema.sql, the find will run a bash shell that does, cat schema.sql | mysql, which is the equivalent of mysql <schema.sql. It will not do mysql ./schema.sql. If you want that, replace the exec with just mysql {} \;
    – Lewis M
    Nov 13, 2018 at 15:41
1

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>.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .