Re: [SQL] bash & postgres

From: Erik Jones <ejones(at)engineyard(dot)com>
To: Greenhorn <user(dot)postgresql(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org, pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] bash & postgres
Date: 2009-03-23 06:31:35
Message-ID: 3FD8F5E0-E3E3-49C6-8A14-398CC68035A4@engineyard.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

On Mar 22, 2009, at 9:03 PM, Greenhorn wrote:

> Hi,
>
> I'm trying to pass variables on a bash script embedded with psql
> commands.
>
> cat header.txt
>
> "to1","from1","subject1"
> "to2","from2","subject2"
> "to3","from3","subject3"
> "to4","from4","subject4"
>
> cat b.sh
>
> #!/bin/bash
> two="2"
>
> psql -h localhost -U postgres -d mobile -c "create temp table header (
>
> field_1 text not null,
> field_2 text not null,
> field_3 text not null
>
> );
>
> \\copy header FROM header.txt CSV
>
> SELECT * FROM header limit "$two"; "
>
>
> When I execute b.sh
> ================================
> ERROR: syntax error at or near "\"
> LINE 10: \copy header FROM header.txt CSV
> ^
>
> How do I use \c (or any other psql commands beginning with a "\") in a
> bash script?

For multi-line input to a psql call in a bash (or any decent shell)
script, I'd use a here document:

#!/bin/bash

#!/bin/bash
two="2"

psql -d pagila <<COPYTEST
create temp table header (

field_1 text not null,
field_2 text not null,
field_3 text not null

);

\copy header FROM header.txt CSV

SELECT * FROM header limit $two;
COPYTEST

$ ./tst.sh
Null display is "\N".
Timing is on.
CREATE TABLE
Time: 7.568 ms
Time: 2.374 ms
field_1 | field_2 | field_3
---------+---------+----------
to1 | from1 | subject1
to2 | from2 | subject2
(2 rows)

Time: 1.011 ms

(P.S. Your quotes around $two in your original are not needed, in fact
they're straight up broken as $two is already inside of a double-
quoted string).

Erik Jones, Database Administrator
Engine Yard
Support, Scalability, Reliability
866.518.9273 x 260
Location: US/Pacific
IRC: mage2k

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Stephen Cook 2009-03-23 06:59:23 Re: text column constraint, newbie question
Previous Message Erik Jones 2009-03-23 06:17:05 Re: pg_restore error - Any Idea?

Browse pgsql-sql by date

  From Date Subject
Next Message Zdravko Balorda 2009-03-23 07:59:12 cast bool/int
Previous Message Erik Jones 2009-03-23 06:17:05 Re: pg_restore error - Any Idea?