Search code examples
postgresqlpsql

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


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?


Solution

  • 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