title: bash scripting - how to properly handle or trap errors for failed database connections
body: <p>I'm writing a bash/shell script that has a <code>psql</code> database connection and the program fails with <code>psql: FATAL:  database "foo" does not exist</code>. This is fine because the program exits since it doesn't exist, but what I would like to do instead is trap or capture that <code>FATAL</code> message and perhaps echo or do something else.</p>
  
  <p>Like if <code>message == "database "foo" does not exist</code>; then echo or run another function.</p>
  
  <p>Here's my line of code that does db connection:</p>
  
  <pre><code>PGPASSWORD=$TARGET_PW "$PSQL" -h "$HOST2" -U masteruser -d "$database" -p 5439 &lt;&lt; EOF 
          \a
          \t
          \o $LISTNEW
      SELECT column_name
      FROM information_schema.columns
      WHERE table_schema = '$SCHEMAMAIN'
      AND table_name   = '$TBL'
      order by ordinal_position;
  EOF
  </code></pre>
  
  <p>Can I get an example of how to do this? thanks.</p>