简体   繁体   English

使用Shell脚本从PostgreSQL检索数据并通过邮件发送

[英]Retrieving data from postgreSQL with a shell script and send it by mail

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 ? 我想每天从我的postgreSQL数据库中检索数据并通过邮件发送结果,最好的方法是什么?

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. 我考虑了一个执行我的SELECT并随后通过邮件功能发送它的shell脚本,但我不知道如何执行SELECT部分​​。

#!/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) EDIT2(更新的代码)

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

You can retrieve data using psql command from postgresql database 您可以使用psql命令从Postgresql数据库检索数据

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

after that you can send output of this command to mail 之后,您可以将此命令的输出发送到邮件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM