install_database.sh
#!/usr/bin/env bash
apt-get install -y mysql-server mysql-client
read -p "Do you want to create a user? [Y/n]: " createuser
if [[ "$createuser" =~ ^[Nn]$ ]]; then
return 0
fi
defaultuser="kriss"
read -p "Enter username for MySQL [default $defaultuser]: " username
if [ -z "$username" ]; then
username="$defaultuser"
fi
read -p "Enter password for MySQL [default $username]: " -s password
if [ -z "$password" ]; then
password="$username"
fi
user_exists=$(mysql -u root -p -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$username')")
if [ "$user_exists" -eq 1 ]; then
echo "User '$username' already exists. Exiting."
return 1
fi
touch "grant.sql"
echo "CREATE USER '$username'@'%' IDENTIFIED WITH mysql_native_password BY '$password';" >> "grant.sql"
echo "GRANT ALL PRIVILEGES ON *.* TO '$username'@'%' WITH GRANT OPTION;" >> "grant.sql"
echo "FLUSH PRIVILEGES;" >> "grant.sql"
echo -e "\n"
echo "--------------"
cat "grant.sql"
echo "--------------"
echo -e "\n"
read -p "Do you want to execute the SQL commands? [Y/n]: " execute
if [[ "$execute" =~ ^[Nn]$ ]]; then
rm "grant.sql"
return 0
fi
mysql -u root -p < "grant.sql"
rm "grant.sql"
echo "Done."