Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I am trying to crate a shell script that would:

  • connect to a remote server that has MYSQL running
  • On success run "CREATE DATABASE foo;"

So far I tried:

#!/bin/bash
mysql -h 111.11.11.11 -u root -p'XXXXXXX'
mysql> CREATE DATABASE foo;

or

echo "CREATE DATABASE foo;";

But no success.

I am using the command line to run the shell script.

# sh create_mysql_database.sh

but all it does is force mysql to connect and wait for input and that is it.

Anyone knows how to actually achieve this?

Server:
Centos 6.2
MySQL client version: 5.1.61

Thanks, Alex

share|improve this question

4 Answers 4

up vote 3 down vote accepted

First of all, there shouldnt be a space between -p and the actual password.

Secondly, as far as I could see from the documentation, you can just add the commands right after the first part, with a -e switch on.

So the final result will look like this:

#!/bin/bash
mysql -h 111.11.11.11 -uroot -pPASSWORD -e "CREATE DATABASE foo;"
share|improve this answer
    
Hi @Frederik I already tried it and it doesnt work, it will give an error "ERROR 1049 (42000): Unknown database 'CREATE DATABASE foo;'". In my example above there is no space between the password (-p'XXXXX') and to make sure that it works I tried running it and it connects successfully, but I cannot pass the command inside the shell script. –  Alex Jul 12 '12 at 13:49
    
Check my updated answer :) –  Frederik Nielsen Jul 12 '12 at 13:50
    
Yes now it works thanks :) –  Alex Jul 12 '12 at 13:52

Id use the mysqladmin command for this type of task:

mysqladmin -u root -pPASSWORD create foo
share|improve this answer
    
Thanks this is a good solution as well –  Alex Jul 12 '12 at 14:51

You should use -e option, like it :

#!/bin/bash
mysql -h 111.11.11.11 -uroot -pPASSWORD -e "CREATE DATABASE foo;"

or :

#!/bin/bash
SQL="CREATE DATABASE foo;"
mysql -h 111.11.11.11 -uroot -pPASSWORD <<<$SQL
share|improve this answer

Believe it or not, you can create a database without logging into mysql.

For example, to create a DB called foo, try the following:

cd /var/lib/mysql
mkdir foo
chown mysql:mysql foo

and you are done !!!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.