0

I have a folder called 'sql' that contains .sql files. I want to write a script that searches for all .sql files, puts the filename into an array, and then kicks off each file.

ie:

 #!/bin/bash

 # Options
 DBHOST=MySQL-hostname
 DBNAME=MySQL-database
 DBUSER=MySQL-username
 DBPASS=MySQL-password

 # Find .sql Files
 ???

 # Create MySQL Tables
 for i in "${TBNAME[@]}"; do
   mysql -h "$DBHOST" -u "$DBUSER" -p"$DBPASS" "$DBNAME" < $TBNAME[$i]
 done

How can I search for .sql files within a specified folder?

2 Answers 2

1
for sqlfile in sql/*.sql ; do
    # do things to $sqlfile
done

For example you can save the full pathnames in a table by using echo "$PWD/$sqlfile"

Sign up to request clarification or add additional context in comments.

1 Comment

Even easier! Thanks so much for your help!
0

Late aswer (after accepted one) but for the record:

printf "source %s\n" sql/**/*.sql | mysql --batch

for this you need to have in the ~/.bash_profile line:

shopt -s globstar #or put this before the above line

How it works:

printf "source %s\n" sql/**/*.sql 

produces lines like

source sql/some/file.sql
source sql/other/file2.sql
#and such...

recursively for all found *.sql files, and the

mysql --batch .... other arguments

will read the "source filename" lines - and executes the sql commands in the files, all in one execution, not need start (run) multiple times the mysql command...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.