Execute several .sql files in a single transaction using PostgreSQL and bash
You can also use the -1
or --single-transaction
option to execute all your scripts in a transaction:
cat file*.sql | psql -1
Either use a sub-shell:
#!/bin/sh
(echo "BEGIN;"; cat file1.sql; cat file2.sql; echo "COMMIT;") \
| psql -U the_user the_database
#eof
or use a here-document:
#!/bin/sh
psql -U the_user the_database <<OMG
BEGIN;
\i file1.sql
\i file2.sql
COMMIT;
OMG
#eof
NOTE: in HERE-documents there will be no globbing, so file*sql will not be expanded. Shell-variables will be expanded, even within quotes.