0

I have a folder with many DB.sql.gz files, i want to import them all into a new installation of MySQL Server in one go.

I thought using bash script would be a good idea.

So Far, I have this file as an executable.

#!/bin/sh
for filename in *.gz; 
do
tempfile="${z##*/}";
database_name = "${tempfile%.*}";
echo database_name;
mysql -pPASS -u USER;
CREATE DATABASE database_name;
unzip z | mysql -pPASS -uUSER database_name;
done

Whats going wrong is that when taking the 'filename' in the for loop, i cant string manipulate to to remove the extension, I want to do this because the database files are named as the database. ( just want to remove the .sql.gz to get the db name )

Help appreciated

4
  • Where do you set $z? Should that be ${filename##*/}? Commented Oct 23, 2014 at 6:06
  • You can't have spaces around = in shell. Commented Oct 23, 2014 at 6:06
  • unzip is for zip files, not gz files. Use gunzip Commented Oct 23, 2014 at 6:06
  • To execute a query direectly using mysql, use mysql -e 'query'` Commented Oct 23, 2014 at 6:08

1 Answer 1

1
#!/bin/sh
for filename in *.gz; 
do
    tempfile="${filename##*/}"
    database_name="${tempfile%%.*}"
    echo $database_name
    mysql -pPASS -u USER -e "CREATE DATABASE $database_name"
    gzcat $filename | mysql -pPASS -uUSER $database_name
done
  1. $z should be $filename.
  2. No spaces around = in assignments
  3. You were missing $ before many variable uses.
  4. To execute the CREATE DATABASE command, use the -e option to mysql
  5. Use gzcat to expand a .gz file to stdout.
  6. ${tempfile%.*} should be ${tempfile%%.*}. % removes the shortest match of the pattern, %% removes the longest match. This will remove all the suffixes.
Sign up to request clarification or add additional context in comments.

5 Comments

Brilliant: there's just one small blip. Unknown database 'xdb.sql' the string needs not to have the .sql part
It should be %%.*, not %.*, so you remove all the suffixes, not just the last one.
Nearly there, it's not creating the Databases, it's creating one called 'database_name' and failing :(
That's another place where you were missing $. Note also that I changed to double quotes there, since variables aren't expanded inside single quotes.
Perfect ! I changed the gzcat to gunzip using --stdout and that got over the gzcat issue i had, but thats the winner !

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.