3

I'm trying to script a query from a bash file but the select query is in a file. For compatibility and test, I'd like to keep it this way.

In short I'd like to write something like:

psql -c data_base "\copy (<file.sql>) To './test.csv' With CSV"

Would you know how to do that ?

EDIT

The "file.sql" contains a query :

$cat file.sql
$SELECT country FROM world;
2
  • Your requirement is not clear. Can you explain it with a sample input and an expected output. Commented Feb 6, 2017 at 10:24
  • The <file.sql> isn't a real sequence. It 's the file containing the query, i'm trying to pass it to the \copy command. Commented Feb 6, 2017 at 10:42

1 Answer 1

8

You can use bash substitution as,

psql -c data_base "\copy ($(<file.sql)) To './test.csv' With CSV"

$(<file) expands the contents of the file

Sign up to request clarification or add additional context in comments.

6 Comments

I have added parentheses because those those are needed when you use a query with COPY.
@LaurenzAlbe: Appreciate it! Cheers!
still testing, ;-) There's issue with a more complex query ( containing parentheses or quotes )
This was very helpful and worked perfectly for me, thanks
I tried the same with $(<file). I am getting -bash: /usr/bin/psql: Argument list too long Edit: My command psql -h DB_HOST DB_NAME DB_USER -c "\copy ($(</tmp/prod_get_carrier_tier_dbcfg.sql)) To './test1.csv' With CSV"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.