Bash script for creating MySQL database
Rate this post

Last Updated on January 29, 2023 by Vikash Ekka

Here is a Bash script that can be used to create a new MySQL database:

#!/bin/bash

# Set the database name and credentials
db_name="mydb"
username="myuser"
password="mypassword"

# Connect to MySQL
mysql -u root -p -e "CREATE DATABASE ${db_name};"

# Create a new user
mysql -u root -p -e "GRANT ALL PRIVILEGES ON ${db_name}.* TO '${username}'@'localhost' IDENTIFIED BY '${password}';"

# Flush privileges
mysql -u root -p -e "FLUSH PRIVILEGES;"

You will need to replace the variables db_name, username, and password with the desired values for your new database.

This script will:

  1. Connect to MySQL with the root user
  2. Create a new database with the name specified in the db_name variable
  3. Create a new user with the name and password specified in the username and password variables, and grant all privileges on the new database to that user
  4. Flush the privileges to make sure the new user has access to the new database

You’ll need to have MySQL installed and running on your machine, and you’ll also need to have the mysql command-line client available in your path.

You can also add further functionality to the script such as checking if the database already exists or not before creating a new one, also you can add a function to import a dump file to the created database and more.

Please let me know if you have any other questions or need further assistance.

By Vikash Ekka

Hi All, My name is Vikash Ekka from India. I’m the founder and tech editor of https://www.vetechno.in. I have completed my Graduation in BCA. I love to write technical articles like Windows, Linux & MAC Tutorials, Tips, Tricks, How To fix, Tutorials About Ethical Hacking & Cyber Security Guide, and Software Review. Currently, I have been working as an IT professional since 2018.

Leave a Reply

Your email address will not be published. Required fields are marked *