使用 shell 脚本 returns 解析 postgres-config.ini 什么都没有,我遗漏了什么吗?

Parsing postgres-config.ini using shell script returns nothing, am I missing anything?

我在 postgres-config.ini 文件中有这些参数:

PGUSER=usr
PGPASSWORD=pass
PGDATABASE=myDB
PGHOST=localhost
PGPORT=5432

我想解析它并使用 shell 脚本(sh 文件)连接到数据库。我像这样使用 source 和 grep 命令:

source <( grep = postgres-config.ini )

但是,当我尝试使用 echo $PGHOST 打印值时,它没有打印任何内容。

任何人都可以帮助我我做错了什么吗?

您的 source 来自进程替换的命令行对我来说工作正常:

$ cat foo.sh
PGUSER=usr
PGPASSWORD=pass
PGDATABASE=myDB
PGHOST=localhost
PGPORT=5432
$ source <(grep = foo.sh)
$ echo $PGHOST
localhost

请注意,shell 变量未导出,因此它们在子流程中不可用。如果您在子流程中需要它们,请尝试:

source <(sed '/=/!d;s/^/export /' foo.sh)

使用 sed 向匹配 =.

的行添加 export 命令

另外,运行 source 你是哪里人?如果是在脚本中,记住变量会在脚本结束时消失,不会传递给父进程。