user2328273
user2328273

Reputation: 968

conditional statement in bash with mysql query

im trying to write a bash script that will do a mysql query and if the number of results is 1, do something. i cant get it to work though.

#!/bin/sh
file=`mysql -uroot -proot -e "select count(*) from MyTable.files where strFilename='file.txt'"`
if [[ $file == "count(*) 1" ]];
then
    echo $file
else 
    echo $file
    echo "no"
fi

i verified the query works. i keep getting this returned

count(*) 1
no

im not sure why but i think it might have something to do with the type of variable $file is. any ideas?

Upvotes: 1

Views: 3193

Answers (3)

Lgrusev
Lgrusev

Reputation: 46

To prevent exposing your database credential in the script you can store them in the local .my.cnf file located in your home directory. This technic will allow your script to work on any server without modification.


Path: /home/youruser/.my.cnf Content:

[client]
user="root"
password="root"
host="localhost"

[mysql]
database="MyTable" 

So, Renato code could be rewritten by following:

#!/bin/sh
file=`mysql -e "select count(*) as count from files where strFilename='file.txt'" | cut -d \t -f 2`
if [ $file == "1" ];
then
    echo $file
else
    echo $file
    echo "no"
fi

Upvotes: 1

Renato Todorov
Renato Todorov

Reputation: 560

I rewrote your script, it works now:

#!/bin/sh
file=`mysql -uroot -proot -e "select count(*) as count from MyTable.files where strFilename='file.txt'" | cut -d \t -f 2`
if [ $file == "1" ];
then
    echo $file
else
    echo $file
    echo "no"
fi

I'm giving a better name to the count field, using 'cut' to split the mysql output into two fields and putting the content of the second field into $file. Then you can test $file for "1". Hope it helps you..

Upvotes: 0

icktoofay
icktoofay

Reputation: 129011

I'm guessing that isn't actually count(*) 1 but instead count(*)\n1 or something. echo $file will convert all the characters in IFS to a space, but == will distinguish between those whitespace characters. If this is the case, echo "$file" will give you a different result. (Notice the quotes.)

Upvotes: 0

Related Questions