将 postgresql 结果存储在 bash 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15242752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
store postgresql result in bash variable
提问by knutella
How to atore a scalar postgresql-value on a bash-variable like in script below?
如何在如下脚本中的 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"
I tried several different writings, but nothing seems to work. Thanks in advance.
我尝试了几种不同的写作,但似乎没有任何效果。提前致谢。
回答by Kouber Saparev
Put the -c
option just before its argument - the query. Mind also using the additional -t
option to get just the tuple value. And of course, use the backticks (`) operator.
将-c
选项放在其参数 - 查询之前。还要注意使用附加-t
选项来获取元组值。当然,使用反引号 ( `) 运算符。
Using the -X
option is also recommended, as sometimes a .psqlrc
file might add some redundant output, as well as the -A
option, which disables column aligning (whitespaces).
-X
还建议使用该选项,因为有时.psqlrc
文件可能会添加一些冗余输出,以及-A
禁用列对齐(空格)的选项。
vartest=`psql -X -A -d $dbname -U $username -h localhost -p 5432 -t -c "SELECT gid FROM testtable WHERE aid='1'"`
回答by Ratnakri
Using -t option or --tuples-only will give you the rows only, so it will easier to store them in array variable (if the result from query more than one)
使用 -t 选项或 --tuples-only 只会为您提供行,因此将它们存储在数组变量中会更容易(如果查询结果不止一个)
vartest =(`psql -t -d $dbname -U $username -c "SELECT gid FROM testtable WHERE aid='1';"`)
echo $vartest
example:
例子:
query result
查询结果
ubuntu@ratnakri:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"
barman
barman2
make it into array variable
使其成为数组变量
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