March 30, 2010

How to execute Mysql query from bash/shell script?

Do you want to execute Mysql query from Bash or KSH shell script?


Command : mysql
Command Options/Switches:
-u or --user=name : Mysql User for login if not current user.
-p or --password[=name] : Mysql Password to use when connecting to server.
Syntax:
mysql -u dbuser --password=dbpassword << eof use dbname;
select * from tablename ;
eof


Example Shell Script -1 : Shows how to display all columns in Mysql table named addressbook from a bash shell script.

!#/bin/bash
mysql -u dbuser --password=dbpassword << eof
use addressbook;
select * from addressbook;
eof

Example Shell Script -2 :


!#/bin/bash

user=`mysqldbuser`
password=`mysqldbpassword`
db=`ebuggi`
table=`addressbook`

mysql -u $user --password=$password << eof
use $db;
select * from $table;
eof
Related:
How to execute Mysql query from Linux shell ?

No comments: