2/13/2013

use select, show databases, show tables, external sql file of mysql by shell script utility

usually we use shell to backup, update the database. Now I give one example for you to use mysql based on shell script.

Four Shell Example for:
select
show databases;
show tables;
sql.sql file

Execute one select command

> ./bash.sh host user dbnam
-------------------------bash.sh-------------------------------------

#!/bin/sh

HOST=localhost
if [ $1 ]
then
   HOST=$1
fi

user=root
if [ $2 ]
then
   user=$2
fi

db=dbname
if [ $3 ]
then
   db=$3
fi

mysql="$(which mysql)"

read -s -p "Please input the db pass: " pass


if [ $pass ]
then

  DBS="$($mysql -h$HOST -u$user -p$pass -D$db -e 'select uid from dd0a05_users limit 0, 10')"

  for db in $DBS
  do
   echo $db
  done

else
   echo 'No db pass'
fi
------------------------------end bash.sh-------------------------------------------


Execute 'show databases' command

> ./bash.sh host user dbnam
-------------------------bash.sh-------------------------------------

#!/bin/sh

HOST=localhost
if [ $1 ]
then
   HOST=$1
fi

user=root
if [ $2 ]
then
   user=$2
fi

db=dbname
if [ $3 ]
then
   db=$3
fi

mysql="$(which mysql)"

read -s -p "Please input the db pass: " pass


if [ $pass ]
then

  DBS="$($mysql -h$HOST -u$user -p$pass  -e 'show databases')"

  for db in $DBS
  do
   echo $db
  done

else
   echo 'No db pass'
fi
------------------------------end bash.sh-------------------------------------------


Execute 'show tables' command

> ./bash.sh host user dbnam
-------------------------bash.sh-------------------------------------

#!/bin/sh

HOST=localhost
if [ $1 ]
then
   HOST=$1
fi

user=root
if [ $2 ]
then
   user=$2
fi

db=dbname
if [ $3 ]
then
   db=$3
fi

mysql="$(which mysql)"

read -s -p "Please input the db pass: " pass


if [ $pass ]
then

  DBS="$($mysql -h$HOST -u$user -p$pass -D$db -e 'show tables')"

  for db in $DBS
  do
   echo $db
  done

else
   echo 'No db pass'
fi
------------------------------end bash.sh-------------------------------------------


Execute external files 'sql.sql' command

> ./bash.sh host user dbnam
-------------------------bash.sh-------------------------------------

#!/bin/sh

HOST=localhost
if [ $1 ]
then
   HOST=$1
fi

user=root
if [ $2 ]
then
   user=$2
fi

db=dbname
if [ $3 ]
then
   db=$3
fi

mysql="$(which mysql)"

read -s -p "Please input the db pass: " pass


if [ $pass ]
then

  DBS="$($mysql -h$HOST -u$user -p$pass -D$db < sql.sql)"

  for db in $DBS
  do
   echo $db
  done

else
   echo 'No db pass'
fi
------------------------------end bash.sh-------------------------------------------









No comments:

Post a Comment