2013-03-06 105 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 
相關問題