将postgresql结果存储在bash变量中
如何在bash变量上存储标量postgresql值,如下面的脚本所示将postgresql结果存储在bash变量中,bash,postgresql,variables,Bash,Postgresql,Variables,如何在bash变量上存储标量postgresql值,如下面的脚本所示 dbname="testlauf" username="postgres" vartest='psql -c -d $dbname -U $username -h localhost -p 5432 "SELECT gid FROM testtable WHERE aid='1';"' echo "$vartest" 我试过几篇不同的文章,但似乎都不管用。提前感谢。将-c选项放在其参数-查询之前。请注意,还可以使用附加的-
dbname="testlauf"
username="postgres"
vartest='psql -c -d $dbname -U $username -h localhost -p 5432 "SELECT gid FROM testtable WHERE aid='1';"'
echo "$vartest"
我试过几篇不同的文章,但似乎都不管用。提前感谢。将
-c
选项放在其参数-查询之前。请注意,还可以使用附加的-t
选项仅获取元组值。当然,使用backticks(`)操作符
还建议使用-X
选项,因为有时.psqlrc
文件可能会添加一些冗余输出,以及禁用列对齐(空白)的-a
选项
使用-t选项或--tuples only将只提供行,因此将它们存储在数组变量中会更容易(如果查询的结果不止一个)
例如:
查询结果
ubuntu@ratnakri:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"
barman
barman2
将其转换为数组变量
ubuntu@ratnakri:~$ RESULT=(`psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"`)
ubuntu@ratnakri:~$ echo ${RESULT[0]}
barman
ubuntu@ratnakri:~$ echo ${RESULT[1]}
barman2
对于命令替换,必须使用反勾号(
`
)或$()
。单引号(“
)不行。谢谢。但即使是vartest=$(psql-c-d testlauf-U postgres-h localhost-p5432“从testtable中选择gid,其中aid='1';”)
也不会起到令人遗憾的作用。。。它给了我“sytnac error near or at“-d”我也用dbname试过了……不知怎的,它吞下了我在这条命令中的后背。。。但事实上,我在作业的第二部分之前和之后都添加了它们。非常感谢Kouber,这就成功了!实际上,backticks似乎对我仍然不起作用,但($)确实起作用:vartest=$(psql-X-h localhost-p 5432-d testlauf-U postgres-c“SELECT gid FROM testtable WHERE aid='1';))如何在远程主机上执行此命令?如何输入数据库密码?
ubuntu@ratnakri:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"
barman
barman2
ubuntu@ratnakri:~$ RESULT=(`psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"`)
ubuntu@ratnakri:~$ echo ${RESULT[0]}
barman
ubuntu@ratnakri:~$ echo ${RESULT[1]}
barman2