Monthly Archives: July 2013

psql – return multiple results in bash

Lets say you want to run a “select” statement against your PostgreSQL database with the tool “psql” in your shell and the query returns values from different columns (like “select A,B,C,D from abc;”) you might do it like this:

psql -A -t -q -c "select A,B,C,D from abc;" -U user -d db

The result looks like this:


You definitely want to have the values in different variables so it is easier to work with them.
I prefer to do it like this

DATA=$(psql -A -t -q -c "select A,B,C,D from abc;" -U user -d db)
ONE=$(echo $DATA | awk -F'|' '{print $1}')
TWO=$(echo $DATA | awk -F'|' '{print $2}')
THREE=$(echo $DATA | awk -F'|' '{print $3}')
FOUR=$(echo $DATA | awk -F'|' '{print $4}')

After this the variables ONE, TWO, THREE and FOUR contain the values from the query.