Search code examples
sqlpostgresqlshellpsqlpostgresql-copy

Handling quotes in COPY to CSV from command shell


I am trying to run this COPY query from the command shell:

COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;

I know you can run queries from the command line using psql:

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

But how can I combine the 2? The below doesn't seem to work but I'm not sure how/if I need to escape.

psql -U username -d mydatabase -c 'COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;'

Solution

  • Don't mix ' and ", quote query with ".

    psql -U username -d mydatabase -c "COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;"