3

I'm making an script in bash in what i run a psql query with this:

VAR="$(psql -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT value FROM table where query = 'query'")"

The problem is the content on $VAR is like this:

value ----------------- result (1 row)

I just need result in my $VAR to use it in the rest of the script.

X3MBoy
  • 203
  • 4
  • 12
  • 2
    This might help you: http://stackoverflow.com/questions/9934264/how-to-hide-result-set-decoration-in-psql-output – zedfoxus Feb 04 '16 at 19:15
  • Does this answer your question? [store postgresql result in bash variable](https://stackoverflow.com/questions/15242752/store-postgresql-result-in-bash-variable) – Duke Mar 12 '20 at 10:36

1 Answers1

1
VAR=`psql -t -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT value FROM table where query = 'query'"`

or

VAR=$(psql -t -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT value FROM table where query = 'query'")

The -t returns only the tuple (data).

See psql documentation about available options.

EDIT

I've been able to use a subsheel as suggested here : https://stackoverflow.com/a/21193276/14673

psql -t -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT value FROM table where query = '`echo $VAR`'"
Community
  • 1
  • 1
Luc M
  • 16,630
  • 26
  • 74
  • 89
  • Did you know if type could be a problem when i use this method? I mean i have: `VAR="$(psql -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT value FROM table1 where query = 'query'")" psql -h prov-db-cl -p 5446 -d prov -U prov -c "SELECT * FROM table2 where query2 = '$VAR'")` And is not working the 2nd query, and i know for sure that the `VAR` value exists in the table2, but it just don't found any result. And guessing some type problems because `$VAR` is an integer, but is used like string because the DB logic – X3MBoy Feb 05 '16 at 13:11
  • 1
    @X3MBoy You can't expand variable into single quotes. See http://stackoverflow.com/questions/21192420/shell-bash-how-to-echo-variables-inside-single-quotes – Luc M Feb 05 '16 at 14:36
  • @X3MBoy Check my edit, I've been able to use a subshell :-) – Luc M Feb 05 '16 at 14:44