#!/bin/bash
# Variables
DB_NAME="your_database_name" # Replace with your PostgreSQL database name
DB_USER="your_db_user" # Replace with the PostgreSQL user
OUTPUT_FILE="/path/to/flat_file.log" # Define the path to the flat file
HOST="localhost" # Hostname of the PostgreSQL server, adjust if necessary
PORT="5432" # Port for PostgreSQL (default: 5432)
# Date and time format
DATE=$(date '+%Y-%m-%d')
TIME=$(date '+%H:%M:%S')
# Capture the database size using psql
DB_SIZE=$(psql -U $DB_USER -h $HOST -p $PORT -d $DB_NAME -t -c "SELECT pg_size_pretty(pg_database_size('$DB_NAME'));" | tr -d ' ')
# Check if DB_SIZE is not empty or null
if [[ -z "$DB_SIZE" ]]; then
echo "[$DATE $TIME] ERROR: Could not fetch the database size" >> $OUTPUT_FILE
else
# Write date, time, and size to the output file
echo "[$DATE $TIME] Database: $DB_NAME Size: $DB_SIZE" >> $OUTPUT_FILE
fi