Shell Script to Perform Database Operations
Last Updated :
30 Jan, 2023
In this article, we will be creating a shell script to perform various database operations. We will be using the MySQL database management system and the MySQL command-line client for our examples. However, the concepts and techniques discussed in this article can be applied to other database management systems as well.
Before we begin, make sure that you have the following prerequisites:
- A MySQL server set up and running
- The MySQL command-line client installed on your machine
- A MySQL user account with the necessary privileges to perform the operations you want to include in your script
Make sure that your MySQL server is running you can start your server by command:
$ service mysql start
You can see below the status is running and my server is active:
Creating the Script
We will start by creating a new file called db_ops.sh using a text editor of your choice. The first thing we will do in our script is to store the MySQL username and password in separate variables. This will make it easier to modify these values later on if needed.
#!/bin/bash
# MySQL login details
MYSQL_USER=”user”
MYSQL_PASSWORD=”password”
Next, we will define a function to execute a MySQL query and print the results to the terminal. This function will take two arguments: the query to execute and the MySQL database to use.
# Function to execute a MySQL query and print the results
execute_query() {
local query=$1
local database=$2
mysql -u “$MYSQL_USER” -p”$MYSQL_PASSWORD” “$database” -e “$query”
}
With these basic building blocks in place, we can now start adding the database operations we want to include in our script. Let’s start by creating a function to create a new database.
# Function to create a new database
create_database() {
local database=$1
execute_query “CREATE DATABASE $database”
}
We can now create a function to create a new table in a database. This function will take three arguments: the name of the database, the name of the table, and the table schema.
# Function to create a new table in a database
create_table() {
local database=$1
local table=$2
local schema=$3
execute_query “CREATE TABLE $table ($schema)” “$database”
}
We can also create functions to insert, update, and delete data from a table. These functions will take similar arguments as the create_table function, with the addition of the data to insert, update, or delete.
# Function to insert data into a table
insert_data() {
local database=$1
local table=$2
local data=$3
execute_query “INSERT INTO $table VALUES ($data)” “$database”
}
# Function to update data in a table
update_data() {
local database=$1
local table=$2
local data=$3
local condition=$4
execute_query “UPDATE $table SET $data WHERE $condition” “$database”
}
# Function to delete data from a table
delete_data() {
local database=$1
local table=$2
local condition=$3
execute_query “DELETE FROM $table WHERE $condition” “$database”
}
Finally, we can create a function to display the data stored in a table. This function will take two arguments: the name of the database and the name of the table.
# Function to display data from a table
display_data() {
local database=$1
local table=$2
execute_query “SELECT * FROM $table” “$database”
}
Now that we have all the functions in place, we can use them in the main body of our script to perform the desired database operations. For example, the following script creates a new database called “employees”, creates a table called “employee_data” with the specified schema, inserts some data into the table, updates a record, and displays the updated data.
# Create a new database
create_database “employees”
# Create a table with the specified schema
create_table “employees” “employee_data” “id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), salary INTEGER”
# Insert data into the table
insert_data “employees” “employee_data” “1, ‘John Smith’, 50000”
insert_data “employees” “employee_data” “2, ‘Jane Doe’, 60000”
# Update a record
update_data “employees” “employee_data” “salary=70000” “id=2”
# Display the data
display_data “employees” “employee_data”
Steps to create and execute a bash script
Step 1: Open a terminal window.
Step 2: Use the nano or vi command to open a new blank file in a text editor.
nano myscript.sh
Step 3: Type the bash commands that you want to include in the script.
Step 4: Save the file by pressing CTRL + X, then Y, and then Enter.
Step 5: Make the script executable by running the chmod command:
chmod +x myscript.sh
Step 6: Run the script by typing its name at the command prompt, followed by any arguments that the script expects:
./myscript.sh
Script:
Output:
You can see in the above image the script is being executed successfully and the output is printed in the terminal.
Conclusion
In this article, we have seen how to create a shell script to perform various database operations using the MySQL database management system. We have created functions to create a database, create and modify tables, and query data. With these building blocks, you can easily create a script to automate any database-related tasks you might have. With these building blocks, you can easily create a script to automate any database-related tasks you might have. For example, you could create a script to regularly back up your database or populate a database with test data for testing purposes. It is important to note that the concepts and techniques discussed in this article can be applied to other DBMS as well. You will just need to use the appropriate command-line tools and SQL commands for the database you are working with. In summary, shell scripts can be a useful tool for automating database operations and streamlining your workflow. I hope this article has been helpful and has given you some ideas on how you can use shell scripts to manage your databases more efficiently.
Similar Reads
How to Run a Shell Script in Linux
Shell scripts are a powerful way to automate tasks and manage system processes in Linux. These scripts, written in shell programming languages like Bash, allow users to execute a sequence of commands efficiently. In this guide, we'll show the steps to check a shell script in Linux before running it,
4 min read
How to Create a Shell Script in linux
Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup
7 min read
How to Show Database in PL/SQL
PL/SQL is the Procedural Language/Structured Query Language and serves as a procedural language built-in extension to SQL language, which allows seamless integration of procedural constructs with SQL. One of the most common functions of a DBMS is the retrieval of information about databases which is
4 min read
Working with Databases in R Programming
Prerequisite: Database Connectivity with R Programming In R programming Language, a number of datasets are passed to the functions to visualize them using statistical computing. So, rather than creating datasets again and again in the console, we can pass those normalized datasets from relational da
4 min read
Bash Script - Write Hello World Program
In this article, we are going to see how to write "hello world" program in Bash script. The bash script is a text file that contains a set of instructions ( i.e. codes or commands ) that can be executed in the terminal. In any programming language, the first program that we learn to write is " Hello
2 min read
Python SQLite - CRUD Operations
In this article, we will go through the CRUD Operation using the SQLite module in Python. CRUD Operations The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let's di
4 min read
How to fetch data from the database in PHP ?
Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create, Read, Update and Delete) operations. In this article, we will discuss the Read part i.e. data fetching from database. There are two ways to connect to a database using PHP. They are as follows. MySQLi ("i"
4 min read
Export SQLite Database To a CSV File
SQLite is an embedded database that doesn't use a database like Oracle in the background to operate. It is written in C language and is used by developers who embed a lightweight database over the existing application, browser, or embedded systems. The main features of SQLite are that it is a tiny,
5 min read
SQL Query to Rename Database
Renaming a database in SQL is an essential task that database administrators and developers frequently perform. Whether youâre reorganizing your data, correcting naming conventions, or simply updating your project structure, knowing how to rename a database properly is critical. In this article, we'
3 min read
Interface Python with an SQL Database
Python is an easy-to-learn language and connectivity of python with any SQL database is a much-desired option to have the persistence feature. Python is an object-oriented programming language and it is open source. Newcomers to the software industry including school children too can learn Python ea
8 min read