Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store postgresql result in bash variable

How to atore a scalar postgresql-value on a bash-variable like in script below?

dbname="testlauf" username="postgres"  vartest='psql -c -d $dbname -U $username -h localhost -p 5432 "SELECT gid FROM testtable WHERE aid='1';"' echo "$vartest" 

I tried several different writings, but nothing seems to work. Thanks in advance.

like image 335
knutella Avatar asked Mar 06 '13 08:03

knutella


People also ask

How do you assign a selected value to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.

Can you use variables in PostgreSQL?

PL/pgSQL variables can have any SQL data type, such as integer , varchar , and char . Here are some examples of variable declarations: user_id integer; quantity numeric(5); url varchar; myrow tablename%ROWTYPE; myfield tablename.


2 Answers

Put the -c option just before its argument - the query. Mind also using the additional -t option to get just the tuple value. And of course, use the backticks (`) operator.

Using the -X option is also recommended, as sometimes a .psqlrc file might add some redundant output, as well as the -A option, which disables column aligning (whitespaces).

In order to skip NOTICE or other additional messages, include the -q flag.

vartest=`psql -d $db -U $user -AXqtc "SELECT gid FROM testtable WHERE aid='1'"` 
like image 97
Kouber Saparev Avatar answered Sep 22 '22 21:09

Kouber Saparev


Using -t option or --tuples-only will give you the rows only, so it will easier to store them in array variable (if the result from query more than one)

vartest =(`psql -t -d $dbname -U $username -c "SELECT gid FROM testtable WHERE aid='1';"`) echo $vartest 

example:

query result

ubuntu@ratnakri:~$ psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots" barman barman2 

make it into array variable

    ubuntu@ratnakri:~$ RESULT=(`psql -h localhost -p 5432 -t -U postgres -d postgres -c "select slot_name from pg_replication_slots"`)     ubuntu@ratnakri:~$ echo ${RESULT[0]}     barman     ubuntu@ratnakri:~$ echo ${RESULT[1]}     barman2 
like image 42
Ratnakri Avatar answered Sep 22 '22 21:09

Ratnakri