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

user494461 picture user494461 · Feb 11, 2015 · Viewed 20k times · Source

Suppose I created a sequence in postgresql:

CREATE SEQUENCE my_seq;

I store the below line in an sql file 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?

Answer

Tom-db picture Tom-db · Feb 11, 2015

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

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

The required psql options mean:

-t only tuple

-A output not unaligned

-q quiet

-X Don't run .psqlrc file