Once a geek, forever a geek…

Bash script to create MySQL database and user

| 2 Comments

Here is a little script I made to quickly and easily create users and databases for MySQL. I only use this for development, for actual deployed applications you would probably want to be more specific about the privileges given:

#!/bin/bash
 
EXPECTED_ARGS=3
E_BADARGS=65
MYSQL=`which mysql`
 
Q1="CREATE DATABASE IF NOT EXISTS $1;"
Q2="GRANT ALL ON *.* TO '$2'@'localhost' IDENTIFIED BY '$3';"
Q3="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}"
 
if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: $0 dbname dbuser dbpass"
  exit $E_BADARGS
fi
 
$MYSQL -uroot -p -e "$SQL"

To use it, just run:

./createudb testdb testuser secretpass

That command would create a database named testdb, and user testuser with the password of secretpass.

Related Posts

Author: Marius Voila

Hi! My name is Marius Voila, and I am a professional system administrator, system architect, and designer.

2 Comments

  1. nice script, but i need to do it in a shared hosting (cpanel) i dnt have access to root, any idea?

  2. If you have cpanel then you have phpmyadmin too..so is easy to create a db in phpmyadmin..and as far as I know you can create DB’s from inside of cpanel

Leave a Reply

Required fields are marked *.

*