1

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?

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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..

Comments

0

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.)

2 Comments

the output i mentioned is exactly how it appears. maybe you could clarify a little, i dont quite understand what you mean.
@user2328273: You're using echo $file. echo $file is different from echo "$file". Try adding quotes and see if you get a newline or tab rather than a space when you echo it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.