Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I return a record in PostgreSQL?

To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ). In the function, we return a query that is a result of a SELECT statement.

What does psql return?

psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs (e.g., out of memory, file not found), 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set.

Why we use $$ in PostgreSQL?

In PostgreSQL, the dollar-quoted string constants ($$) is used in user-defined functions and stored procedures. In PostgreSQL, you use single quotes for a string constant like this: select 'String constant'; When a string constant contains a single quote ('), you need to escape it by doubling up the single quote.


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


Try:

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