Import psql dump without change in pg_hba.conf?

Abstract: Import a PostgreSQL dump using psql without modifying pg_hba.conf by passing connection details via environment variables or command-line arguments.

Created: 2026-09-13 by
You can import a PostgreSQL dump without modifying pg_hba.conf by leveraging environment variables to specify the connection details directly in your command line. This approach bypasses the need for persistent configuration changes, allowing you to authenticate and connect using specific host, port, user, and password parameters provided at runtime. By setting these variables or passing them as arguments, you maintain a clean configuration file while ensuring secure and flexible database restoration processes on Linux systems.

Understanding the Role of pg_hba.conf

The pg_hba.conf file is responsible for controlling client authentication in PostgreSQL. It determines which hosts are allowed to connect, which databases they can access, and what authentication methods (such as md5, scram-sha-256, or peer) are required. Modifying this file requires restarting the PostgreSQL service or reloading the configuration, which can be disruptive in production environments. Often, users encounter issues when trying to import dumps because the default connection settings do not match the authentication rules defined in this file. Instead of editing global settings, it is safer and more efficient to provide explicit connection parameters during the import operation.

Using Environment Variables for Connection

One of the most robust ways to handle connections without touching configuration files is through environment variables. The PostgreSQL client tools, including psql, recognize several standard environment variables that override default connection behavior. By exporting these variables before running your import command, you ensure that the tool connects exactly where you intend, using the credentials you provide. This method is particularly useful in scripts or automated tasks where configuration files should remain immutable. To use this method, you must set the following variables:
  • PGHOST: Specifies the host name of the machine running the database server. If omitted, it defaults to a Unix domain socket.
  • PGPORT: Sets the TCP port or local Unix domain socket file extension. The default is usually 5432.
  • PGUSER: Defines the PostgreSQL user name to connect as. If not specified, it defaults to the current operating system user name.
  • PGPASSWORD: Provides the password for the specified user. Note that storing passwords in plain text in environment variables can have security implications, so use with caution in shared environments.
For example, you can run the import command like this:
export PGHOST=localhost
export PGPORT=5432
export PGUSER=myuser
export PGPASSWORD=mypassword
psql -d mydb < dump.sql
This ensures that psql uses the provided credentials rather than relying on the system user or default socket connections that might be blocked by pg_hba.conf.

Passing Parameters Directly in the Command

If you prefer not to export environment variables, you can pass connection parameters directly to the psql command using long options. This is often cleaner for one-off commands as it keeps all necessary information in a single line. The -h flag specifies the host, -p sets the port, -U defines the user, and -d selects the database. However, note that the password cannot be passed as a command-line argument due to security restrictions regarding process visibility in the system's process list. Instead, you can use the -w flag to suppress password prompts if you are using a password file, or rely on the PGPASSWORD environment variable for that specific value. Alternatively, you can use a .pgpass file to store connection credentials securely without exposing them in the command line or environment variables. This file should be located in the user's home directory and have strict permissions (readable only by the owner). Here is an example of a direct command invocation:
psql -h localhost -p 5432 -U myuser -d mydb -f dump.sql
When you run this, psql will prompt for the password. You can type it in, or if you have configured a .pgpass file, it will use that automatically. This approach avoids any changes to pg_hba.conf because you are explicitly defining the connection endpoint and user.

Handling Authentication Errors

If you still encounter authentication errors despite providing correct parameters, check the PostgreSQL logs for detailed error messages. Common issues include mismatched hostnames (using localhost vs 127.0.0.1), incorrect port numbers, or users that do not exist in the database cluster. Remember that pg_hba.conf rules are evaluated in order, and the first matching rule is used. Ensure that your connection attempt matches a valid rule in the file. For instance, if your rule allows host connections from 127.0.0.1/32 but you connect via ::1 (IPv6 localhost), it may fail depending on how your network stack resolves localhost. In such cases, you can test connectivity using pg_isready to verify that the server is accepting connections on the specified host and port. This diagnostic step helps isolate whether the issue is with the network layer or the authentication layer. If pg_isready succeeds but psql fails, the problem is likely related to user permissions or password hashing algorithms.

Security Considerations

While avoiding changes to pg_hba.conf is convenient, it is crucial to maintain security best practices. Avoid hardcoding passwords in scripts or shell history. Use .pgpass files or integrated authentication methods where possible. Additionally, restrict the scope of the database user to only the necessary privileges for the import task. Importing large dumps can also impact system performance, so monitor resource usage during the process. For further assistance with related Linux database management tasks, you might find the guide on How to Shrink Sparse Files in Linux After Copying Without the -S Operator helpful for managing disk space after large imports. Similarly, understanding process management can aid in troubleshooting if the import process is killed unexpectedly, as discussed in How to find out exactly which process was killed by OOM killer?.

Frequently Asked Questions

Can I use psql without a password prompt?

Yes, you can set the PGPASSWORD environment variable to avoid interactive prompts. Alternatively, configure a .pgpass file in your home directory to store credentials securely, which psql will read automatically.

Why does my connection fail even with correct credentials?

Check if the host specification matches the rules in pg_hba.conf. Using localhost might resolve to IPv6 (::1) while the rule only allows IPv4 (127.0.0.1), causing a mismatch. Try specifying 127.0.0.1 explicitly.

Is it safe to export passwords in environment variables?

It is generally safe for short-lived sessions but visible in environment listings. For better security, use .pgpass files with restricted permissions or integrate with system authentication mechanisms like Kerberos or LDAP.

What if I need to import a dump from a remote server?

Use the -h flag to specify the remote host IP or domain name. Ensure that the remote server's pg_hba.conf allows connections from your IP address and that network firewalls permit traffic on the PostgreSQL port.

How do I verify if PostgreSQL is ready to accept connections?

Run the pg_isready command with the appropriate host and port flags. It returns immediately if the server is accepting connections, helping you diagnose network or service availability issues before attempting an import.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More