n1ghtie
9/26/2016 - 2:12 PM

bash script usage, $ sh database_init.sh $dbname $dbuser $dbuserpwd. Script creates a new database, assigns user with all previleges and cre

bash script usage, $ sh database_init.sh $dbname $dbuser $dbuserpwd. Script creates a new database, assigns user with all previleges and creates a pwd for that user. Also updates the .env variable with the same credentials. !important this script must run in root laravel folder.

#!/bin/bash
green=`tput setaf 2`
reset=`tput sgr0`
red=`tput setaf 1`
ok() { echo $1; }

envf() {
	sed -i '' "s/DB_DATABASE=homestead/${1}/g" .env
	sed -i '' "s/DB_USERNAME=homestead/${2}/g" .env
	sed -i '' "s/DB_PASSWORD=secret/${3}/g" .env
	echo "${green}Successfully modified .env file${reset}";
}

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 "${red}Usage: $0 dbname dbuser dbpass${reset}"
  exit $E_BADARGS
fi
 
$MYSQL -u homestead -psecret -e "$SQL"

ok "Database ${green}$1${reset} and user ${green}$2${reset} created with a password ${green}$3${reset}!"
envf "DB_DATABASE=$1" "DB_USERNAME=$2" "DB_PASSWORD=$3"