Techtrekking

Shell Script to to take back of database

By Pravin

Here is sample shell script to take back of existing database. Before running the script, run following command, it will add execute permission to a file so it can be run as a program/script.

chmod +x script_name

How to run the script

./script_name

Here is sample shell script

#!/bin/bash # ========= CONFIG ========= DB_HOST="localhost" DB_PORT="5432" DB_NAME="database_name" DB_USER="database_user_name" DB_PASSWORD="database_user_password" BACKUP_DIR="/user/project/backup" # ========================== # Create backup directory if not exists mkdir -p "$BACKUP_DIR" # Export password for pg_dump export PGPASSWORD="$DB_PASSWORD" # Date format DATE=$(date +"%Y-%m-%d") # Output file BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_${DATE}.sql" echo "Starting backup of database: $DB_NAME" echo "Backup file: $BACKUP_FILE" pg_dump \ -h "$DB_HOST" \ -p "$DB_PORT" \ -U "$DB_USER" \ -F p \ "$DB_NAME" > "$BACKUP_FILE" # Check result if [ $? -eq 0 ]; then echo "Backup completed successfully." else echo "Backup failed!" exit 1 fi # Unset password unset PGPASSWORD
Comments
No comments yet. Be the first to comment!
Leave a Comment
Your comment will be visible after approval.