将postgresql结果存储在bash变量中

问题描述:

如何像下面的脚本那样在bash变量上赋予标量postgresql值?

How to atore a scalar postgresql-value on a bash-variable like in script below?

dbname="testlauf"
username="postgres"

vartest='psql -c -d $dbname -U $username -h localhost -p 5432 "SELECT gid FROM testtable WHERE aid='1';"'
echo "$vartest"

我尝试了几种不同的著作,但似乎没有任何效果。

I tried several different writings, but nothing seems to work. Thanks in advance.

-c 选项放在其前面参数-查询。注意,还可以使用附加的 -t 选项仅获取元组值。当然,请使用反引号(`)运算符。

Put the -c option just before its argument - the query. Mind also using the additional -t option to get just the tuple value. And of course, use the backticks (`) operator.

使用 -X 还建议使用>选项,因为有时 .psqlrc 文件可能会添加一些冗余输出,以及 -A 选项,该选项将禁用列对齐(空格)。

Using the -X option is also recommended, as sometimes a .psqlrc file might add some redundant output, as well as the -A option, which disables column aligning (whitespaces).

vartest=`psql -X -A -d $dbname -U $username -h localhost -p 5432 -t -c "SELECT gid FROM testtable WHERE aid='1'"`