knu*_*lla 28 postgresql variables bash
如何在bash-variable上创建标量postgresql-value,如下面的脚本?
dbname="testlauf"
username="postgres"
vartest='psql -c -d $dbname -U $username -h localhost -p 5432 "SELECT gid FROM testtable WHERE aid='1';"'
echo "$vartest"
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的着作,但似乎没有任何作用.提前致谢.
Kou*_*rev 51
将-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'"`
Run Code Online (Sandbox Code Playgroud)
Rat*_*kri 11
使用 -t 选项或 --tuples-only 只会为您提供行,因此将它们存储在数组变量中会更容易(如果查询结果不止一个)
vartest =(`psql -t -d $dbname -U $username -c "SELECT gid FROM testtable WHERE aid='1';"`)
echo $vartest
Run Code Online (Sandbox Code Playgroud)
例子:
查询结果
ubuntu@ratnakri:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"
barman
barman2
Run Code Online (Sandbox Code Playgroud)
使其成为数组变量
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
Run Code Online (Sandbox Code Playgroud)