Bash MySQL query

I am trying to run a query against MySQL 5.6.35 in bash and let it complete 0 if the value is greater than or equal to 14. I can make it show the results that I would expect, but not output 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 executed bash script:

~# ./check.sh
39
./check.sh: line 6: test: too many arguments
CRITICAL

UPDATE WITH ANSWER:

This is how I thanked this for the help of codeforester

#!/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

Conclusion:

~# ./check.sh
OK
+4
source share
1 answer

You get an error too many argumentsbecause the unspecified $querycalculates a lot of words that confuse test. I am sure that you do not intend to test the request, but the results of the request. So you should use command substitution to output MySQL output:

query_output=$(mysql -u root -sN weekly_db -e "$query")

(( ... )), :

if ((query_output >= 14)); then
  echo "OK"
  exit 0
else
  echo "CRITICAL"
  exit 2
fi

MySQL ( ) , - if false, else . , .


. :

+5

Source: https://habr.com/ru/post/1677277/


All Articles