Sanyifejű
Sanyifejű

Reputation: 2740

how to assign a query result to a shell variable

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.

Upvotes: 1

Views: 3345

Answers (1)

anubhava
anubhava

Reputation: 784998

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"

Upvotes: 2

Related Questions