Re: multiple sql results to shell

From: Geoff Winkless <pgsqladmin(at)geoff(dot)dj>
To: Mark Lybarger <mlybarger(at)gmail(dot)com>, Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: multiple sql results to shell
Date: 2017-10-23 14:24:14
Message-ID: CAEzk6fcbw8PMR4+ThP0GQ6jWDaPNJBwhijGSjbbDWVrZJk70Kg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 23 October 2017 at 15:08, Mark Lybarger <mlybarger(at)gmail(dot)com> wrote:
> I have this bash/sql script which outputs some curl commands. the backticks
> causes it to get interpreted by the shell. This works fine if there is one
> result, but when there are many rows returned, it looks like one shell
> command.
>
> any help on getting multiple rows returned to be executed by the shell would
> be appreciated!

I tend to do

psql ..... | while read a; do
# some code
done

The only problem I find with this is that you can't pass variables out
of the while loop, because the pipe runs as a subshell. You could of
course use echo and encapsulate the whole thing, eg this would take
your results and (assuming they're integers) return the largest -
obviously your own code could decide differently how to output things.
You also have to move the read to later on, so you can send your
output to the parent.

myres=$(
a=0
biga=0
psql -tqAX -h ${DB_HOST} -d ${DB_NAME} -u ${DB_USER} -c "select
'curl -X POST http://${REGISTER_HOST}:8080/' || source_id || '/${MT}/'
|| model || '/' || site || '/backoffice/register' from
myschema.events where source_id = $SOURCE_ID and ineffective_date is
null" | while true; do
if [ $a -gt $biga ] ; then
biga=$a
fi
if ! read a; then echo $biga; break; fi
done
)

A mess, but it works.

To be honest, by the time you've got to this level of complexity you
probably shouldn't be using shellscript any more.

Geoff

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Hunčár 2017-10-23 14:44:27 table corruption
Previous Message David G. Johnston 2017-10-23 14:19:03 Re: multiple sql results to shell