Using a Shell Script to Connect to a Postgres (Redshift) database and table

3k Views Asked by At

I need help understanding some pieces of a shell script to connect to a Redshift database because Bash/shell is unfamiliar for me.

  1. to use pgpass, is this all I need to get the credentials? :

    cat > ./.pgpass <<-CREDS
    $HOSTNAME:$PORT_NUMBER:$DBNAME:$USERNAME:$PASSWORD
    CREDS
    
  2. What is <<-? Is it a comment? Quick search says that <<END is a comment but is that anything different from <<-CREDS?

  3. This is somewhat related to #2, what do <<-ATOMIC and \x mean in this snippet?

    $PSQL_CMD <<-ATOMIC
    \x
    SELECT column1 FROM $THETABLE WHERE column1='true';
    ATOMIC  
    

Since ATOMIC is at the end of this block, I would presume that it's stating the end of a block or something, but I don't understand the documentation or anything.

  1. How do I assign the returned value(s) of the SELECT statement into a variable and echo it into an email? I have a line to send the email, but don't know how to assign the returned values from the SELECT query into a variable:

    $ echo "hello world" | mail -s "Test" [email protected]
    
1

There are 1 best solutions below

0
On
  1. I'm not sure what you're trying to do here. To my knowledge, pgpass won't contain your credentials unless you've put them in there yourself. This sounds like maybe command to do that.

  2. <<- is not a comment. It represents a 'Here document' See: https://en.wikipedia.org/wiki/Here_document#Unix-Shells

  3. Regarding <<-ATOMIC see the above link. The \x tells psql to format the output from your SELECT

  4. OUTPUT = `psql -U username -h host -d dbname tablename -c $PSQL_CMD'
    echo $OUTPUT | mail -s "Test" [email protected]