The following code is used to move the PostgreSQL data directory to a new directory.

# Move the data directory for PostgreSQL 15
# This script moves the data directory for PostgreSQL 15 to a new location.

# Stop PostgreSQL 15 service
sudo systemctl stop postgresql-15

# Create the new data directory for PostgreSQL 15
sudo mkdir -p /var/lib/postgresql/15/main
sudo mkdir -p /etc/postgresql/15/main

# Copy the data directory from PostgreSQL 15 to PostgreSQL 15
sudo rsync -av --progress /var/lib/pgsql/15/data/ /var/lib/postgresql/15/main/

# Move Configuration files to the new location
sudo cp /var/lib/pgsql/15/data/postgresql.conf /etc/postgresql/15/main/
sudo cp /var/lib/pgsql/15/data/pg_hba.conf /etc/postgresql/15/main/
sudo cp /var/lib/pgsql/15/data/pg_ident.conf /etc/postgresql/15/main/

# Change ownership of the new data directory
sudo chown -R postgres:postgres /var/lib/postgresql/15/main
sudo chown -R postgres:postgres /etc/postgresql/15/main

# Edit the PostgreSQL 15 configuration file
# Replace the data_directory and hba_file paths in the configuration file
# with the new paths to the moved data directory and configuration files.
sudo nano /etc/postgresql/15/main/postgresql.conf

# data_directory = '/var/lib/postgresql/15/main'          # use data in another directory
#                                                         # (change requires restart)
# hba_file = '/etc/postgresql/15/main/pg_hba.conf'        # host-based authentication file
#                                                         # (change requires restart)   
# ident_file = '/etc/postgresql/15/main/pg_ident.conf'    # ident configuration file
#                                                         # (change requires restart)
# # If external_pid_file is not explicitly set, no extra PID file is written.
# external_pid_file = '/var/run/postgresql/15-main.pid'   # write an extra PID file
#                                                         # (change requires restart)

# Edit the systemd service file for PostgreSQL 15
sudo systemctl edit postgresql-15.service
# If the service file does not exist, create it:
sudo nano /etc/systemd/system/postgresql-15.service

# Add the following content to the service file:
# [Service]
# Environment=PGDATA=/var/lib/postgresql/15/main
# ExecStart=
# ExecStart=/usr/pgsql-15/bin/postgres -D ${PGDATA} -c config_file=/etc/postgresql/15/main/postgresql.conf

# Use the correct path to the PostgreSQL 15 binary in the ExecStart line.
# ExecStart=/usr/pgsql-17/bin/postgres -D ${PGDATA} -c config_file=/etc/postgresql/15/main/postgresql.conf


# Reload the systemd daemon to apply the changes
sudo systemctl daemon-reload

# Start PostgreSQL 15 service
sudo systemctl start postgresql-15


# Compare directory sizes
sudo du -sh /var/lib/pgsql/15/data
sudo du -sh /var/lib/postgresql/15/main

# Remove the old data directory if everything is working fine
sudo rm -rf /var/lib/pgsql/15

By Rudy