Execute a MySQL command from a shell script

I was having trouble creating databases and their users with permission when automating with bash shell script. In this post, I will show you how to execute the mysql or mariadb command using bash shell script, as well as an alternate method. 

Method 1: Using Bash shell

You need to use the following command in order to execute the mysql quiey.

mysql -h <host> -u<user> -p<password> database -e \
  "SELECT * FROM table_name WHERE id='007';"

Single line command for bash shell

mysql -h <host> -u<user> -p<password> database_name_here -e "SELECT * FROM table WHERE id='007';"

Method 2: Using .sql file

with .sql we can import the quiry using given command.

mysql -h "<host_ip_here>" "--user=<username_here>" "--password=<password_here>" "--database=<database_name_here>" < "filename.sql"

Or you can use the given command, “Recommend.

mysql -h "host_ip_here" -u "username_here" -p "database_name_here" < "sqlfile.sql"

Conclusion

We have successfully execute the mysql quiiey in bash shell script, Kindly report in case you are facing defeculties with follwing details.

  • OS name
  • OS version
  • Package name
  • Logs – Error / Warning / failed

Get in touch with our new devops tools based website- https://www.devopstricks.in/

Execute a MySQL command from a shell script

One thought on “Execute a MySQL command from a shell script

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top