title: How to save a postgres query to a file from a remote computer
body: <p>I have a script which outputs some data from a postgres database:</p>
  
  <pre><code>#!/bin/bash
  
  dbname="inventory"
  username="postgres"
  NOW=$(date +"%d-%m-%Y-%H%M%S")
  OUTPUT="output.$NOW"
  
  psql $dbname $username &lt;&lt; EOF
  \o | cat &gt;&gt; $OUTPUT
  select count(*) from component;
  select * from product where procode='AAA';
  \q
  \o
  EOF
  </code></pre>
  
  <p>This happily exports the data I need to a text file if I run it on the local machine.</p>
  
  <p>Now I want to do the same thing for 10 remote computers and have the output stored in one file on the machine I run the script from.  I have the following code that will grep some information from the remote machines but I also need to add the postgres data above to my $FILE_OUT below:</p>
  
  <pre><code>#!/bin/bash
  
  NOW=$(date +"%d-%m-%Y-%H%M%S")
  dbname="inventory"
  username="postgres"
  
  echo "Enter the file name"
  read FILE_IN
  FILE_OUT="invcheck.$NOW"
  
  for i in $(cat $FILE_IN); do
  echo $i &gt;&gt; $FILE_OUT
  
  ssh user@$i "ps -efw | grep TRADINGTIMEPLUS /opt/jrms/jrms.ini" &gt;&gt; $FILE_OUT
  </code></pre>
  
  <p>I have tried to put the postgres code in a line like:</p>
  
  <pre><code>ssh rmsasi@hj$i "psql $dbname $username &lt;&lt; EOF \o | cat &gt;&gt; $FILE_OUT select * from component where code='1000';\q;\o; EOF"
  </code></pre>
  
  <p>but I get errors and the postgres data is not included in the $FILE_OUT</p>
  
  <pre><code>psql: warning: extra option o ignored
  cat: from: No such file or directory
  cat: component: No such file or directory
  cat: where: No such file or directory
  cat: code=1000: No such file or directory
  bash: line 1: q: command not found
  bash: line 1: o: command not found
  bash: line 1: EOF: command not found
  </code></pre>
  
  <p>I am only new to scripting so hopefully I am just missing something simple.</p>
  
  <p>My thanks in advance and if there is a better way to do what I am trying to achieve I appreciate any pointers.</p>