48

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335

2 Answers2

91

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Tom-db
  • 6,528
  • 3
  • 30
  • 44
  • 1
    @eric-leschinski, why did you add the `-X` option? I think, this option in not needed in this case. – Tom-db Nov 08 '17 at 07:39
  • The `~/.psqlrc` file performs operations upon database login that dump noise to the output which is caught up into your `VALUE` variable, that noise was removed with the -X option. – Eric Leschinski Nov 08 '17 at 07:41
  • 1
    ok, this was you case, but is it generally valid? The psqlrc file could also perform operations which are needed for running the query – Tom-db Nov 08 '17 at 07:46
4

Try:

LAST_VALUE=`echo "SELECT last_value FROM my_seq;" | psql -qAt -d database_name`
Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63