1

I have an sql query that returns a date. I call this query from a shell script and would like to assign this value to the variable called datestart (and use it later). Here is my code. Without the datestart assignment the query works fine.

#!/bin/sh
firstname="-Upgsql"
dbname="statcoll"
portname="-p5438"
datestart=(psql $firstname $portname $dbname<< EOF
SELECT MIN(latestrefdate) FROM (SELECT MAX(referencedate) AS latestrefdate FROM statistics WHERE transactionname IN(SELECT DISTINCT transactionname FROM statistics WHERE platform = 'Smarties')GROUP BY transactionname) as earliest;
EOF
)
echo $datestart

but the result is this :

 Syntax error: word unexpected (expecting ")"). 

I have no idea where should I insert that closing bracket. Any hint is appreciated.

Sanyifejű
  • 2,610
  • 10
  • 46
  • 73

1 Answers1

2

Instead of brackets in variable assignment you need to use $(...) for BASH or `...` for sh.

Try this:

#!/bin/sh

firstname="-Upgsql"
dbname="statcoll"
portname="-p5438"
datestart=`psql -t --pset="footer=off" --user="$firstname" --port="$portname" -d "$dbname"<<EOF
SELECT MIN(latestrefdate) FROM (SELECT MAX(referencedate) AS latestrefdate FROM statistics WHERE transactionname IN (SELECT DISTINCT transactionname FROM statistics WHERE platform = 'Smarties') GROUP BY transactionname) as earliest;
EOF
`
echo "$datestart"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    I really recommend `$(..)` over backticks, backticks don't work at all when used inside of each other, while nested expressions are fine using `$(..)` – scragar Jun 16 '14 at 14:34
  • yes, it almost solved my problem. Instead of the actual date value the content of the header gets assigned to the variable. So I expect something like this '2014-05-23' but got 'min ----- (1 row)' instead – Sanyifejű Jun 16 '14 at 14:34
  • That is due to column header and footer text. See [this Q&A](http://dba.stackexchange.com/questions/24215/how-to-turn-off-header-only-in-psql-postgresql) – anubhava Jun 16 '14 at 14:37
  • Also check updated answer and this: http://stackoverflow.com/questions/9934264/how-to-hide-result-set-decoration-in-psql-output – anubhava Jun 16 '14 at 14:42