You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

psql为何未读取PGHOST和PGPORT环境变量?

问题:psql未读取/etc/bash.bashrc中配置的PGHOST/PGPORT环境变量

已将PGHOST和PGPORT添加至/etc/bash.bashrc,且能正常输出变量值、ping通远程服务器:

$ echo $PGHOST
db_host
$ echo $PGPORT
19000
$ ping db_host
PING db_host (172.16.2.160) 56(84) bytes of data.
64 bytes from db_host (172.16.2.160): icmp_seq=1 ttl=64 time=0.565 ms
64 bytes from db_host (172.16.2.160): icmp_seq=2 ttl=64 time=0.925 ms

但直接运行psql时出现连接错误,仍尝试连接本地默认端口:

$ psql
psql: error: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

通过命令行指定参数psql -h $PGHOST -p $PGPORT可正常连接远程服务器。

补充:本地与远程均为Ubuntu Server 22.04系统、Postgres 13版本。


解决方法

1. 确认环境变量已正确导出

如果在/etc/bash.bashrc中仅设置变量而未添加export,子进程(如psql)无法继承这些变量。修改文件内容:

sudo nano /etc/bash.bashrc

添加或修改为:

export PGHOST=db_host
export PGPORT=19000

保存后执行以下命令使配置立即生效:

source /etc/bash.bashrc

验证变量是否已导出:

export | grep PG

2. 检查当前使用的shell类型

如果当前shell不是bash,/etc/bash.bashrc不会被加载。执行以下命令查看当前shell:

echo $SHELL
  • 若输出为/usr/bin/zsh,则需将变量添加到/etc/zsh/zshrc或~/.zshrc中,格式同样为export PGHOST=db_host
  • 若需切换回bash,执行bash后再测试psql

3. 处理非交互式/非登录shell的加载问题

部分场景下(如脚本执行、非登录shell启动),/etc/bash.bashrc可能不会被加载。可将变量添加到全局环境配置文件/etc/environment:

sudo nano /etc/environment

添加内容:

PGHOST=db_host
PGPORT=19000

注意:此文件中不需要export关键字,保存后重启系统或重新登录即可生效。

4. 检查/etc/bash.bashrc的权限

确保文件权限正确,bash才能正常加载它:

ls -l /etc/bash.bashrc

正常权限应为-rw-r--r-- 1 root root,若权限异常,执行以下命令修复:

sudo chmod 644 /etc/bash.bashrc
sudo chown root:root /etc/bash.bashrc

内容的提问来源于stack exchange,提问作者Ubuntu Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:35:29