psql执行存储的函数并将结果存储在变量中

时间:2018-11-21 08:15:19

标签: bash psql

我需要执行sql函数并存储结果

#!/bin/bash  
RESULT=`psql -A -t postgresql://user:password@localhost:5432/db -c "select main.return_anything();" db`
echo $RESULT

并期望结果包含1

但是我得到了结果

psql: warning: extra command-line argument "select main.return_anything();" ignored
psql: warning: extra command-line argument "db" ignored

它只是在等待某些东西,不会产生任何结果。有什么问题吗?

1 个答案:

答案 0 :(得分:1)

来自psql manual

psql [option...] [dbname [username]]

所以第一个选项,然后是dbname,然后是用户名。

尝试一下:

RESULT=$(psql -A -t -c "select main.return_anything();" postgresql://user:password@localhost:5432/db db)

侧面说明:不推荐使用反引号`。使用$(...)看起来更干净并允许嵌套。