Run MySQL commands from the Bash command line

MySQL 5.

You can run MySQL commands by logging into the MySQL shell or by redirecting a file into mysql with mysql -u[user] -p[pass] [database] < [filename].

You can also execute MySQL commands directly from the Bash command line using the -e flag:

mysql -u[user] -p[pass] -e "[mysql commands]"

Or as follows:

mysql -u[user] -p[pass] <<QUERY_INPUT
[mysql commands]
QUERY_INPUT

Note that in that previous example the last QUERY_INPUT must not be preceeded by any spaces.

Example

The following examples create a database called 'test_database'.

Either:

mysql -usteph -pblah -e "create database test_database"

Or:

mysql -usteph -pblah <<QUERY_INPUT
create database test_database;
QUERY_INPUT

Last modified: 21/02/2007 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top