How to execute a MySQL Command from a Linux Bash Shell?

Sometimes it is necessary to runMySQL query directly from theLinux Command Line without actually going into the interactive MySQL prompt.

For example, when you want to schedule a backup of MySQL databases or automate a creation of MySQL databases and users with some Bash Script.

Use one of the following commands to run a MySQL query from a Linux command line.

MySQL Command From a Bash Shell in One Line

Use the following command for quickly execution of MySQL query from a Linux Bash Shell :
# mysql -u [user] -p[pass] -e “[mysql commands]”
Example :
# mysql -u root -pSeCrEt -e “show databases”

Run a MySQL Query From a Bash script using EOF

Use the following syntax in your Bash scripts for running MySQL commands :
mysql -u [user] -p[pass] << EOF
[mysql commands]

Example :

mysql -u root -pSeCrEt << EOF
use mysql;
show tables;

Execute a MySQL Command Remotely

Use -h option to specify a MySQL server’s IP address:
# mysql -h [ip] -u [user] -p[pass] -e “[mysql commands]”
Example :
# mysql -h -u root -pSeCrEt -e “show databases”

Specify a Database to Use

Use -D option to specify the name of MySQL database :
# mysql -D [db name] -u [user] -p[pass] -e “[mysql commands]”
Example :
# mysql -D clients -u root -pSeCrEt -e “show tables”