:::: MENU ::::

Bash script for adding MySQL users

Now that we’re using Amazon EC2 for our lab computing needs, I find I’m doing many server maintenance tasks over and over again. One of my least favorites is adding new MySQL users. So, I wrote a bash script that makes adding them easier. You can get the script at our Github organization or see the code after the jump.

#!/bin/bash

EXPECTED_ARGS=2
E_BADARGS=65
MYSQL=`which mysql`

Q1="CREATE USER '$1'@'localhost' IDENTIFIED BY '$2';"
Q2="GRANT ALL PRIVILEGES ON *.* TO '$1'@'localhost';"
Q3="CREATE USER '$1'@'%' IDENTIFIED BY '$2';"
Q4="GRANT ALL PRIVILEGES ON *.* TO '$1'@'%';"
Q5="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}${Q4}${Q5}"

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: $0 dbuser dbpass"
  exit $E_BADARGS
fi

$MYSQL -uroot -p -e "$SQL"

So, what do you think ?

You must be logged in to post a comment.