PostgreSQL的psql客户端如何获取select字段的变量

How to get the variables of the select field in the psql client of PostgreSQL

在 psql 客户端中:运行

select pg_backend_pid() ospid \gset

\echo :ospid

这样可以获得ospid值;

但是:我想将 ospid col 值回显到文件

\! echo 'a' :ospid 'b' > /tmp/test.log

我该如何解决? 谢谢。

正如the documentation所说:

Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \!, and neither variable interpolation nor backquote expansion are performed in the arguments.

您可以使用 \g 来解决这个问题:

test=> \pset format unaligned
Output format is unaligned.
test=> \pset tuples_only
Tuples only is on.
test=> SELECT pg_backend_pid() ospid \gset
test=> SELECT 'a ' || :ospid  || ' b' \g /tmp/test.log

谢谢@Laurenz Albe。

我的目标是设置终端标题。

我解决这个问题

\pset tuples_only on
\pset border 0

SELECT user,pg_backend_pid() ospid  \g  ./_ospid.log

\echo '******** ospid:=[':ospid']   user:=[':user']********'

\! echo -ne '3]0;'`cat ./_ospid.log`'[=10=]7' ;


\pset tuples_only off
\pset border 2