Friday 2 November 2018

Execute Mysql Command in Bash / Shell Script

Q) How to connect to mysql database from a bash script in unix or linux and run sql queries?


Bash scripting helps in automating things. We can automate running sql queries by connecting to the mysql database through a shell script in unix or linux system.

Linux Tutorial and Materials, LPI Guides, LPI Learning, LPI Study Material, LPI Learning

Here we will see how to run a small sql query in mysql database through a script. The bash script code is shown below:

#!/usr/bin/bash

#Script to run automated sql queries

#Declaring mysql DB connection 

MASTER_DB_USER='username'
MASTER_DB_PASSWD='password'
MASTER_DB_PORT=3160
MASTER_DB_HOST='mysql.hostname'
MASTER_DB_NAME='mysqlDbName'

#Prepare sql query

SQL_Query='select * from tablename limit 10'

#mysql command to connect to database

MYSQL -u$MASTER_DB_USER -p$MASTER_DB_PASSWD -P$MASTER_DB_PORT -h$MASTER_DB_HOST -D$MASTER_DB_NAME <<EOF 
$SQL_Query
EOF
echo "End of script"

Here in the above script, the first part declares the mysql db variables and assigns the DB details. The second part prepares sql query. And the final part executes the mysql command.

Related Posts

0 comments:

Post a Comment