Skip to content

Instantly share code, notes, and snippets.

@wannadrunk
Last active January 27, 2022 00:23
Show Gist options
  • Save wannadrunk/f17fe94b108d13199d3f20b127ff12fc to your computer and use it in GitHub Desktop.
Save wannadrunk/f17fe94b108d13199d3f20b127ff12fc to your computer and use it in GitHub Desktop.
Bash script to dump the Postgresql DB and send the notification to LINE Notify
#!/bin/bash
### Author: cHoo
### Date: August 2019
### Description: Script to dump database.
### Version:
#### 1.01 - update messages.
#### 1.10 - 20210912 backup file size.
# Import global variable in this setting-global is consisting of LINE API key
CONFLE="/opt/scripts/setting-global.ini"
if [ -f $CONFLE ]
then
source $CONFLE
LINEMSG="$HOSTNAME: $0"
else
LOGTIME=`date '+%Y-%m-%d_%H:%M:%S'`
LINETOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
LINEMSG="$0 - $LOGTIME - Config not found."
curl -X POST -H "Authorization: Bearer $LINETOKEN" -F "message=$LINEMSG" https://notify-api.line.me/api/notify
echo -e "\n"
exit
fi
# define the variables
BAKDIR="/data/bak"
BAKLOG="$BAKDIR/bkup_db.log"
BAKTIME=`date '+%Y%m%d_%H%M'`
LOGTIME=`date '+%Y-%m-%d_%H:%M:%S'`
LINEMSG+="\n\n$LOGTIME - Backup start"
# Start the backup
## log to file.
echo -e "\n--- Daily Backup $LOGTIME ---" >> $BAKLOG
echo -e " $LOGTIME - Start to vacuum and dump the databases. " >> $BAKLOG
cd $BAKDIR
DBS=`psql -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | grep -v CTc | awk {'print $1'}`
for i in $DBS; do
# Dump DB
LOGTIME=`date '+%Y-%m-%d_%H:%M:%S'`
echo -e " $LOGTIME - DB: $i - Dump. " >> $BAKLOG
/usr/bin/pg_dump $i -f $BAKTIME-$i.sql
SQLSZE=`du -h $BAKTIME-$i.sql | awk {'print $1'}`
# Compress dump file
LOGTIME=`date '+%Y-%m-%d_%H:%M:%S'`
echo -e " $LOGTIME - DB: $i - Compress. " >> $BAKLOG
tar -cz --remove-files -f $BAKTIME-$i.tgz $BAKTIME-$i.sql >> $BAKLOG 2>&1
TGZSZE=`du -h $BAKTIME-$i.tgz | awk {'print $1'}`
LOGTIME=`date '+%Y-%m-%d_%H:%M:%S'`
echo -e " $LOGTIME - DB: $i DONE. " >> $BAKLOG
LINEMSG+="\n$LOGTIME db $i ($SQLSZE/$TGZSZE)"
done
# Script runtime
ENDTIME=`date +%s`
RUNTIME=$((ENDTIME-STARTTIME))
RUNSEC=$(($RUNTIME%60))
RUNMIN=$(($RUNTIME/60))
LINEMSG+="\nElapse time: $RUNMIN min. $RUNSEC seconds"
# LINE Notify
LINEMSG=`echo -e $LINEMSG`
curl -X POST -H "Authorization: Bearer $LINETOKEN" -F "message=$LINEMSG" https://notify-api.line.me/api/notify
## Send to Telegram, require TGAPI and CHATID, should define in setting-global.ini
# curl -X POST https://api.telegram.org/bot$TGKEY/sendmessage -d "chat_id=$CHATID" -d "text=$LINEMSG"
echo -e "\n"
@wannadrunk
Copy link
Author

ตัวที่ revise ล่าสุดถูกรวบรวมไว้ที่ https://github.com/WhereWeCanShare/SysAdminDoc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment