Skip to content

Instantly share code, notes, and snippets.

@kendrickjr
Last active January 11, 2023 19:50
Show Gist options
  • Save kendrickjr/38ab7361a7eea25eda3b87ef729812fa to your computer and use it in GitHub Desktop.
Save kendrickjr/38ab7361a7eea25eda3b87ef729812fa to your computer and use it in GitHub Desktop.
Postgres Backup Script

Here's an example of a simple script that can be used to backup a PostgreSQL database using the pg_dump command:

#!/bin/bash
# Set the name of the database you want to backup
database=mydb

# Set the name of the backup file
backup_file=mydb_$(date +%Y%m%d).bak

# Set the path to the backup file
backup_path=~/backups

# Set the username and password for the database
db_user=myuser
db_password=mypassword

# Create the backup
pg_dump -U $db_user -W -F t $database -f $backup_path/$backup_file

# Check if the backup was created successfully
if [ $? -eq 0 ]; then
  echo "Backup created successfully: $backup_path/$backup_file"
else
  echo "Error: Backup failed"
fi

This script uses the pg_dump command to create a plain-text SQL file backup of the specified database (in this example "mydb"). The -U option is used to specify the database user, the -W option is used to prompt for the password, and the -F option is used to specify the format of the backup file (in this case, "t" for plain-text). The -f option is used to specify the name of the backup file.

The script will check if the backup was created successfully, if so it will print "Backup created successfully: $backup_path/$backup_file" and if not it will print "Error: Backup failed"

You can adjust the script according to your needs, for example you could add more options to the pg_dump command to further control the backup process. You might also consider adding the script to a cron job to schedule automatic backups.

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