Initdb: error: directory “/var/lib/postgresql/data” exists but is not empty

The error message “initdb: error: directory ‘/var/lib/postgresql/data’ exists but is not empty” occurs when trying to initialize a PostgreSQL database cluster, but the target directory already exists and contains files or folders.

This error usually happens when attempting to run the “initdb” command after a failed or partial installation, where the target directory was not cleaned up properly.

To fix this issue, you have a few options:

  1. Remove existing files: If you don’t need the data inside the existing PostgreSQL data directory, you can simply delete its contents before running “initdb” again. Be cautious as this will permanently delete any existing databases and their data. Here’s a command you can use:

            $ sudo rm -rf /var/lib/postgresql/data/*
          
  2. Specify a different target directory: If the current directory contains important data that you don’t want to delete, you can choose a different directory to initialize the PostgreSQL database cluster. You can specify the target directory using the “–pgdata” option when running “initdb”. For example:

            $ initdb --pgdata=/path/to/new/directory
          
  3. Use an existing empty directory: If you have another empty directory that you want to use for the new PostgreSQL database cluster, you can specify it as the target directory when running “initdb”. For example:

            $ initdb --pgdata=/path/to/existing/empty/directory
          

It’s important to note that handling the contents of the data directory requires appropriate permissions. You may need to run the commands with administrative privileges or use “sudo” to gain the necessary permissions.

Remember to adjust the specific directory paths and command options according to your system configuration.

Read more interesting post

Leave a comment