A good[ish] website

Web development blog, loads of UI and JavaScript topics

Shell script to create MySQL database and user

Filed under: Server— Tagged with: MySQL, shell, snippets

Simple bash script to quickly create a MySQL database and a user.

This can come pretty handy if you need to make a lot of databases, while doing a server migration, or something like that.

Usage instructions

The script takes three parameters:

  1. Database name
  2. Database username
  3. And a password

Name it something like, then make it executable:

$ sudo chmod 755

And run it:

$ sudo ./ my-database my-user c00lp45w0rd

Here’s the piece of bash code:


green() {
  echo -e '\e[32m'$1'\e[m';

readonly EXPECTED_ARGS=3
readonly E_BADARGS=65
readonly MYSQL=`which mysql`

# Construct the MySQL query
readonly Q2="GRANT ALL ON *.* TO '$2'@'localhost' IDENTIFIED BY '$3';"
readonly SQL="${Q1}${Q2}${Q3}"

# Do some parameter checking and bail if bad
if [ $# -ne $EXPECTED_ARGS ]
  echo "Usage: $0 dbname dbuser dbpass"
  exit $E_BADARGS

# Run the actual command
$MYSQL -uroot -p -e "$SQL"

# Let the user know the database was created
green "Database $1 and user $2 created with a password you chose"

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!