abcreddy
abcreddy

Reputation: 102

Redirection of MySQL Queries into a log/text file in shell script and read the file for particular string


I have written a shell script MySQL_Test.sh to connect to the MySQL database from linux shell and execute three different select statements like the following,

Select count(*) as My_Column_Name from <table_name> where <condition>

My shell script looks like the following.

mysql -u$MASTER_DB_USER -p$MASTER_DB_PASSWD -P$MASTER_DB_PORT -h$MASTER_DB_HOST <<EOF
$BS_Query 
$Exp_Query
$ROI_Query
EOF

Now my requirements are,
1. I would like to redirect the output of the three above queries into a single text or log file.
2. Send an email if any of the query returns > 0 rows.
3. Attach the text/log file while sending the email.

Could anyone please help me in fixing 1 and 2. Thanks in advance.

Upvotes: 0

Views: 1818

Answers (1)

Sylvain B
Sylvain B

Reputation: 513

mysql -u$DB_USER -p$PASSWD -P$DB_PORT -h$DB_HOST <<EOF > output.txt
$BS_Query 
$Exp_Query
$ROI_Query
EOF

# For each even line (i.e. containing the count(*) result), test if count(*) != 0
line_number=1
for line in `cat output.txt`; do
  if [ $((line_number % 2)) -eq 0 ]; then
    if [ $line -ne 0 ]; then
      `( echo "Here is your report"; uuencode output.txt output.txt ) | mail -s "SQL report" admin@sqldb`
      exit
    fi
  fi
  line_number=$((line_number + 1))
done

Upvotes: 1

Related Questions