Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to execute multiple MySQL commands using shell script

Tags:

bash

shell

mysql

I would like to write a *.sh script to execute multiple MySQL commands.

Currently, what I can do is something like the following

mysql -h$host -u$user -p$password -e "drop database $dbname;" mysql -h$host -u$user -p$password -e "create database $dbname;" mysql -h$host -u$user -p$password -e "another MySQL command" ... 

Is there a way to avoid typing " mysql -h$host -u$user -p$password -e" every time I want to execute a MySQL command?

like image 992
Brian Avatar asked Sep 30 '15 14:09

Brian


People also ask

How run multiple SQL queries in shell script?

sh script to execute multiple MySQL commands. mysql -h$host -u$user -p$password -e "drop database $dbname;" mysql -h$host -u$user -p$password -e "create database $dbname;" mysql -h$host -u$user -p$password -e "another MySQL command" ...

How do I run multiple queries in MySQL?

MySQL also supports the execution of a string containing multiple statements separated by semicolon ( ; ) characters. This capability is enabled by special options that are specified either when you connect to the server with mysql_real_connect() or after connecting by calling mysql_set_server_option() .

What is shell script in MySQL?

The scripting shell is not only useful for expanding MySQL Workbench. You can use a script file from the scripting shell command line to perform repetitive tasks programmatically. Note. MySQL also has a product named MySQL Utilities, which is different than Workbench Scripting Shell. PDF (US Ltr) - 17.0Mb.


1 Answers

I think you can execute MySQL statements from a text file, for example

here is the cmds.txt file which contains MySQL commands:

select colA from TableA; select colB from TableB; select colC from TableC; 

To execute them using shell script, type

mysql -h$host -u$user -p$password db_dbname < cmds.txt 

This way, you separate your MySQL commands from your shell script.

You may want your script to display progress information to you. For this you can invoke mysql with "--verbose" option.

For more information, see https://dev.mysql.com/doc/refman/5.6/en/mysql-batch-commands.html

like image 72
EricWang Avatar answered Oct 09 '22 02:10

EricWang