I'm trying to run a query against MySQL 5.6.35 in bash, and have it exit 0 if the value is greater than or equal to 14. I can get it to show the results I would expect, but not exit 0.
Script:
#!/bin/bash
query="SELECT count(*) FROM weekly WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK)"
mysql -u root -sN weekly_db -e "$query";
if test $query -ge 14 ; then
echo "OK"
exit 0
else
echo "CRITICAL"
exit 2
fi
Here is the bash script executed:
~# ./check.sh
39
./check.sh: line 6: test: too many arguments
CRITICAL
UPDATE WITH ANSWER:
Here is how I went about this thanks for codeforester's help
#!/bin/bash
query="SELECT count(*) FROM weekly WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK)"
OUTPUT=$(mysql -u root sN weekly_db -e "$query";)
if ((OUTPUT >= 14)) ; then
echo "OK"
exit 0
else
echo "CRITICAL"
exit 2
fi
Output:
~# ./check.sh
OK
$querymagically-ge 14? It's a SQL string.bashis really the worst possible way to get data out of MySQL. If you can use Python, Ruby, Perl, Node.js, anything with a native MySQL driver you'll be far better off. Writing a simple wrapper script and mapping your result to an exit status code sobashcan interpret it is pretty easy.bashis really the worst possible tool for this since it doesn't understand MySQL at all. You can do this with a lot ofsed,awkand other random duct tape, but you really don't want to. This is like four lines in any common scripting language where you can install a MySQL driver.