将PostgreSQL查询结果存储到Shell或PostgreSQL变量
例如,我有一个表存储值:
For instance, I have a table stores value:
select * from myvalue;
val
-------
12345
(1 row)
如何将 12345
保存到Postgresql或Shell脚本中的变量中?
How can I save this 12345
into a variable in postgresql or shell script?
这是我在shell脚本中尝试过的操作:
Here's what I tried in my shell script:
var=$(psql -h host -U user -d db <<SQLSTMT
SELECT * FROM myvalue;
SQLSTMT)
但是 echo $ var
给我:
val ------- 12345 (1 row)
我也尝试过
\set var (select * from myvalue)
在psql中,当我键入 \set
时,它会列出:
in psql and when I type \set
it lists:
var = '(select*frommyvalue)'
不,不,不!使用psql中的原始数据开关(例如 -t或 \t),并将查询通过管道传递给psql,而不是解析ascii-table,请执行:-)
No, no, no! Use "raw data" switch from psql, like "-t" or "\t" and pipe the query to psql instead of parsing ascii-table, come on :-)
echo 'select * from myvalue;' | psql -t -h host -U user -d db
如果您确实需要解析psql输出,则可以也可以使用-H开关(打开HTML输出),并使用一些perl模块来解析html表,我曾经使用过它一两次。此外,您可能希望使用 pgpass文件和 〜/ .psqlrc
用于某些默认设置,例如未指定时连接的默认DB
If you really need parse psql output, you could also use -H switch ( turns on HTML output ), and parse it with some perl module for parsing html tables, I used that once or twice.. Also, you may want to use a pgpass file and ~/.psqlrc
for some defaults, like default DB to connect, when not specified.