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]" [email protected]

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" [email protected]

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" [email protected]
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks a lot. Just edited my post to add my code. Can I just assign your command to my variables ?
Thanks. I update my code but I get an error whhen I execute my script : could not change directory to "/root"
I fixed this error. The mail is comming with the date but the other fields are empty.

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.