postgresql 如何将值从 psql 返回到 bash 并使用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28451598/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:47:07  来源:igfitidea点击:

How to return a value from psql to bash and use it?

postgresqlpsql

提问by Tommaso Di Bucchianico

Suppose I created a sequence in postgresql:

假设我在 postgresql 中创建了一个序列:

CREATE SEQUENCE my_seq;

I store the below line in an sql file get_seq.sql

我将以下行存储在 sql 文件 get_seq.sql 中

SELECT last_value FROM my_seq;

$SUDO psql -q -d database_bame -f get_seq.sql

How do I get the int number returned by SELECT into bash and use it?

如何将 SELECT 返回的 int 数字放入 bash 并使用它?

回答by Tommaso Di Bucchianico

You can capture the result of a command using the VAR=$(command) syntax:

您可以使用 VAR=$(command) 语法捕获命令的结果:

VALUE=$(psql -qtAX -d database_name -f get_seq.sql)
echo $VALUE

The required psql options mean:

所需的 psql 选项意味着:

-tonly tuple

-t只有元组

-Aoutput not unaligned

-A输出未对齐

-qquiet

-q安静的

-XDon't run .psqlrc file

-X不要运行 .psqlrc 文件

回答by Lorenzo Marcon

Try:

尝试:

LAST_VALUE=`echo "SELECT last_value FROM my_seq;" | psql -qAt -d database_bame`