How to execute a MySQL command in a Bash Linux script

To execute a MySQL command in a Bash Linux script follow these steps:

To avoid entering the password manually, you need to use the -p flag and specify the password immediately without a space.

$ mysql -h "server-name" -u "root" "-pXXXXXXXX" "database-name" < "filename.sql"

If the -p flag is followed by a space, the MySQL client will interactively ask for the password, and then it interprets the next command argument as the database name:

$ mysql -h "server-name" -u "root" -p "XXXXXXXX" "database-name" < "filename.sql"
Enter password: <you type it in here>
ERROR 1049 (42000): Unknown database 'XXXXXXXX'

You can store your username and password in the file ~/.my.cnf. In this case, you do not need to pass the name and password as parameters to the command line:

[client]
user = root
password = XXXXXXXX

Then:

$ mysql -h "server-name" "database-name" < "filename.sql"