title: Execute several .sql files in a single transaction using PostgreSQL and bash
body: <p>Say I have the files:</p>
  
  <pre><code>file1.sql
  file2.sql
  file3.sql
  </code></pre>
  
  <p>I need all three files to be executed in a single transaction. I'm looking for a bash script like:</p>
  
  <pre><code>psql -h hostname -U username dbname -c "
  begin;
  \i file1.sql
  \i file2.sql
  \i file3.sql
  commit;"
  </code></pre>
  
  <p>This fails with an error: <code>Syntax error at or near "\"</code>.</p>
  
  <p>I also tried connecting to the DB first and then executing the fails, like that:</p>
  
  <pre><code>psql dbname
  begin;
  \i file1.sql
  \i file2.sql
  \i file3.sql
  commit;
  </code></pre>
  
  <p>This also fails, because the 'begin' command executes only when the connection is terminated.</p>
  
  <p>Is it possible to execute several .sql files in a single transaction using PostgreSQL and bash?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The rough structure of each of the files is similar:</p>
  
  <pre><code>SET CLIENT_ENCODING TO 'WIN1251';
  \i file4.sql
  \i file5.sql
  &lt;etc&gt;
  RESET CLIENT_ENCODING;
  </code></pre>