2013-03-06 107 views
19

如何在下面的脚本中为bash变量赋予标量postgresql-value?在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" 

我尝试了几个不同的着作,但似乎没有任何工作。提前致谢。

+0

对于命令替换,您必须使用反引号('\'')或'$()'。单引号(''')不会。 – 2013-03-06 08:56:42

+0

谢谢。但是即使vartest ='$(psql -c -d testlauf -U postgres -h localhost -p 5432“SELECT gid FROM testtable WHERE aid ='1';”)'不会做不幸的事情......它让我“sytnac错误附近或在”-d“”我也试着用dbname ... – knutella 2013-03-06 09:03:12

+0

..某种方式,它吞下我的后腿在这个coammands ...但实际上我加入他们之前和之后的第二部分作业。 – knutella 2013-03-06 09:06:51

回答

33

-c选项放在其参数 - 查询之前。也请注意使用额外的-t选项来获取元组值。当然,使用反引号(`)运算符。

使用-X选项也被推荐,因为有时一个.psqlrc文件可能增加一些冗余输出,以及所述-A选项,即禁用柱对准(空格)。

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

非常感谢库伯,这个伎俩!其实反引号似乎仍然不适用于我,但(美元):vartest = $(psql -X -h localhost -p 5432 -d testlauf -U postgres -c“SELECT gid FROM testtable WHERE aid ='1' ;“) – knutella 2013-03-06 10:04:39

+0

谢谢。加工。 – 2016-11-03 06:29:33

0

使用-t选项或--tuples只会给你只的行,所以它会更容易将它们存储在数组变量(如与查询不止一个结果)

vartest =(`psql -t -d $dbname -U $username -c "SELECT gid FROM testtable WHERE aid='1';"`) 
echo $vartest 

例如:

查询结果

[email protected]:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots" 
barman 
barman2 

使之变成数组变量

[email protected]:~$ RESULT=(`psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"`) 
    [email protected]:~$ echo ${RESULT[0]} 
    barman 
    [email protected]:~$ echo ${RESULT[1]} 
    barman2 
相关问题