1

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.

1 Answer 1

5

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. 
3
  • Actually now I got this error: ./check.sh: line 7: [: too many arguments because $count return count(column) 1 when I echoed it Commented Feb 16, 2017 at 6:30
  • So the question is how to just check if exist or no.. must return only 1/0 not whole name like count(column) 1 Commented Feb 16, 2017 at 6:59
  • I fixed my answer, I tested it this time and it works. Please try that Commented Feb 16, 2017 at 14:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.