fbpx

PostgreSQL Backup Using Bash Script

PostgreSQL backup using bash script

To create a backup of a PostgreSQL database using a Bash script, you can use the pg_dump command. This command allows you to dump the contents of a database to a file, which can then be used as a backup.

Here is an example of a Bash script that creates a backup of a PostgreSQL database:

				
					#!/bin/bash

# Set the database name and the backup file name
DB_NAME="database"
BACKUP_FILE="database_backup.sql"
date=date=$(date '+%Y-%m-%d')

# Set the username and password for the database
DB_USERNAME="username"
DB_PASSWORD="password"

# Dump the database to a file
pg_dump -U $DB_USERNAME -W $DB_NAME > $BACKUP_FILE_${date}
echo "Database has been done on ${date}" >> /tmp/backup_log_${date}.log

				
			

This script will create a backup of the database named mydatabase and save it to a file called mydatabase_backup.sql. The script uses the pg_dump command to dump the contents of the database to the file, and it specifies the username and password for the database so that pg_dump can connect to it.

You can then use the cron command to schedule this script to run regularly, so that you have regular backups of your database. For example, to run the script every day at midnight, you could add the following line to your crontab file:

				
					0 0 * * * /path/to/my/script/backup_script.sh

				
			

This will run the backup_script.sh script every day at midnight, ensuring that you have regular backups of your database.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories