Using the PG* environmental variables to make your shell scripts more terse.

For unit testing at a certain place I once worked for, this came in handy for database setup/teardown scripts. We would use the PG* environmental variables in our shell scripts, so that instead of running psql with -U for user and -h for host, we would allow it to pick up PGUSER and PGHOST from the environment we were running the shell script in. For safety, we would use bash's ability to provide a default for each PG* environmental variable as we were setting it. This worked quite well.

#!/bin/bash

set -e
set -u

# Set these environmental variables to override them,
# but they have safe defaults.
export PGHOST=${PGHOST-localhost}
export PGPORT=${PGPORT-5432}
export PGDATABASE=${PGDATABASE-my_database}
export PGUSER=${PGUSER-my_user}
export PGPASSWORD=${PGPASSWORD-my_password}

RUN_PSQL="psql -X --set AUTOCOMMIT=off --set ON_ERROR_STOP=on "

${RUN_PSQL} <<SQL
select blah_column 
  from blahs 
 where blah_column = 'foo';
rollback;
SQL