Automating PostgreSQL Backups on Linux a Guide

By Chandrashekhar Fakirpure

Updated on May 09, 2024

In this article, we'll explain about automating PostgreSQL backups on Linux a guide.

To take an automatic backup of a PostgreSQL database on Linux, we can create a shell script that utilizes the pg_dump utility provided by PostgreSQL. Here's a simple example of how we can do this:

1. Create a shell script

First, we need to create a shell script and name the file


Add following contents in the file:


# Define PostgreSQL database credentials

# Define backup directory and filename
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

# Execute pg_dump to backup the database
pg_dump -U "$DB_USER" "$DB_NAME" > "$BACKUP_FILE"


  • Replace DB_USER and DB_NAME with your database name and user.
  • Replace BACKUP_DIR path.

2. Make the script executable

We need to make the script executable so that the crontab will run the file.

chmod +x

3. Set up a cron job

Set up a cron job to execute the script at desired intervals. For example, to run the backup script daily, open your crontab file:

crontab -e

And add the following line to run the script at midnight every day:

0 0 * * * /path/to/

Note: Replace /path/to/ to your file path

This will create a backup of your PostgreSQL database daily at midnight and store it in the specified backup directory with a timestamped filename.

That's it. We have successfully seen automating PostgreSQL backups on Linux a guide.