When working with MySQL it is often necessary to execute SQL statements or scripts programmatically from the command line. SQL statements can be included in a SQL script (text) file and executed by the MySQL Client. This can be done in a few different ways.
Execute MySQL Script File from Standard Input
Statements in a SQL scripts can be read from standard input on a Unix/Linux command line and executed. Two examples of doing this can be seen below.
#!/bin/bash
# redirect standard input from sql script
mysql < sample_script.sql
# cat mysql script and pipe output to mysql client
cat sample_script.sql | mysql
Execute MySQL Script File from MySQL Shell
While running the MySQL shell, SQL scripts can be executed using the source
or \.
commands.
mysql> source sample_script.sql
mysql> \. sample_script.sql
Using the --verbose
Option
Using the --verbose
option when executing MySQL scripts on the command line will print the individual SQL statements before the are executed.
#!/bin/bash
# redirect standard input from sql script
mysql --verbose < sample_script.sql
# cat mysql script and pipe output to mysql client
cat sample_script.sql | mysql --verbose