bash
  • postgresql
  • variables
  • 2013-03-06 8 views 19 likes 
    19

    下のスクリプトのように、bash-variableにスカラーpostgresql-valueを適用する方法はありますか?postgresqlの結果をbash変数に保存します

    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

    コマンド置換では、バッククォート( '\' ')または' $() 'のいずれかを使用する必要があります。一重引用符( '')は使用できません。 –

    +0

    ありがとうございます。しかし、さらにvartest = '$(psql -c -d testlauf -U postgres -h localhost -p 5432"テストツールをどこから選択しても助かりました= '1'; ")'それは不幸なことではありません。 "sytnac error nearまたは" -d ""私もdbnameで試しました... – knutella

    +0

    ..このコマンサスで私のバックスティックを呑み込むのですが、実際には割り当ての第2部の前後に追加しました。 – knutella

    答えて

    33

    -cオプションを引数の直前に置く - クエリ。また、追加の-tオプションを使用してタプル値だけを取得することも忘れないでください。そして、もちろん、バックティック(`)演算子を使用してください。時々.psqlrcファイルが列整列(空白)を無効に-Aオプション、ならびに、いくつかの冗長出力を追加する可能性があるとして-Xオプションを使用

    もまた、推奨されます。それは簡単に配列変数に格納するだろう-tオプションまたは使用

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

    ありがとうクーバー、これはトリックです!実際にはバックティックはまだ動作していないようですが、$(psql -X -h localhost -p 5432 -d testlauf -U postgres -c "SELECT gid FROM testtable WHERE aid = '1' ; ") – knutella

    +0

    ありがとうございます。ワーキング。 –

    0

    --tuplesを専用の行のみあなたを与えるだろう、ので、(もし1以上のクエリからの結果)

    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 
    
    関連する問題