Search code examples
mysqlbashterminalmamp

Terminal function to create database. Bash to Mysql?


Hi I am trying to write an alias to create a database, (its actually going to be part of a bigger local development setup alias) and I am wondering how to pass commands into the MYSQL command line from an alias.

Here is what I have so far

function createDB()
{
        /Applications/MAMP/Library/bin/mysql --host=localhost -uroot -proot; 
        CREATE DATABASE $1;
        \q;
}

alias crDB=createDB;

So that I can call

crDB test

But the problem is, it runs the first line, then opens the mysql command line tool and does not execute any more of the commands until the mysql command line is exited.


Solution

  • To execute a command you can use the -e switch:

    function createDB()
    {
        /Applications/MAMP/Library/bin/mysql --host=localhost -uroot -proot -e "CREATE DATABASE $1"
    }
    

    You may also wish to enclose the database name in backticks, which should be escaped:

    "CREATE DATABASE \`$1\`"