Mysql – Select remote database from bash

bashMySQLshellshell-scripting

I'm kind of new in bash/shell scripting and I'm trying to remotely select from mysql database and check if record exist or no. Based on respond will do some stuff.

This is what I have as a command

mysql -u mysql -pMysql123 -h xxx.xxx.xxx.xxx MYDBNAME -e "select count(column) from TABLE where column=1234;"

When I run this command directly in terminal I've got correct response. So I'm trying to put it in the script like this

#!/bin/bash

count=mysql -u mysql -pMysql123 -h xxx.xxx.xxx.xxx MYDBNAME -e "select count(column) from TABLE where column=1234;"

if [ $count -gt 0 ]
then
     echo " greater that 0 "
else
     echo " lower than 0 "
fi

When I execute above script the output is

$ ./check.sh

./check.sh: line 3: -u: command not found

./check.sh: line 5: [: -gt: unary operator expected

lower than 0

Appreciate any help on this. Thanks.

Best Answer

you need a subshell. try this:

count=$(mysql -u mysql -pMysql123 -h xxx.xxx.xxx.xxx MYDBNAME -sse "select count(column) from TABLE where column=1234;")

if [ $count -gt 0 ]
then
     echo " greater that 0 "
else
     echo " lower than 0 "
fi

also take note of the -s option:

--silent, -s
Silent mode. Produce less output. This option can be given multiple times to produce less and less output.