1

I want to daily retrieve data from my postgreSQL database and send the results by mail, what is the best way to do it please ?

I think about a shell script that execute my SELECT and then send it with mail function but I do not know how to do the SELECT part.

#!/bin/sh
todayDate = $(date);
nbUsers = mySelect;
nbPosts = mySelect;

echo "We are ".$date." dans there are ".$nbUsers." users and ".$nbPosts." posts " | mail -s "[DAILY]" test@test.com

EDIT (Updated code) :

#!/bin/sh
todayDate=$(date +%y%m%d%H%M%S)
nbUsers=$(su postgres -c "psql -d database -c 'SELECT COUNT(*) FROM table1'")
nbPosts=$(su postgres -c "psql -d database -c 'SELECT COUNT(*) FROM table2'")

echo "We are $todayDate. There are $nbUsers users and $nbPosts posts." | mail -s "[DAILY] Databse" test@test.com

EDIT2 (Updated code)

#!/bin/sh
su - postgres
todayDate=$(date +"%d/%m/%y")
todayTime=$(date +"%T")
nbUsers=$(psql -A -t -d database -c "SELECT COUNT(id) FROM table1;")
nbPosts=$(psql -A -t -d database -c "SELECT COUNT(id) FROM table2;")
echo "We are $todayDate. There are $nbUsers users and $nbPosts posts." | mail -s "[DAILY] Databse" test@test.com
fallais
  • 577
  • 1
  • 8
  • 32
  • possible duplicate of [Postgresql query from bash script as postgres user](http://stackoverflow.com/questions/18223665/postgresql-query-from-bash-script-as-postgres-user) – Tomas Greif Jun 11 '14 at 11:42

1 Answers1

2

You can retrieve data using psql command from postgresql database

nbUsers=`su postgres -c "psql -d databasename -c 'SELECT * FROM tableName'"`

after that you can send output of this command to mail

Rahul R Dhobi
  • 5,668
  • 1
  • 29
  • 38
  • Hi, thanks a lot. Just edited my post to add my code. Can I just assign your command to my variables ? – fallais Jun 11 '14 at 11:42
  • Thanks. I update my code but I get an error whhen I execute my script : **could not change directory to "/root"** – fallais Jun 11 '14 at 12:23
  • I fixed this error. The mail is comming with the date but the other fields are empty. – fallais Jun 11 '14 at 15:00