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

psql execute stored function and store the result in the variable

我需要执行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

而且它只是在等待什么,并没有产生任何结果。有什么问题?

来自psql manual

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

所以首先是选项,然后是可选的 dbname,然后是可选的用户名。

试试这个:

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

旁注:反引号 ` 已弃用。使用 $(...) 看起来更干净并允许嵌套。