Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a database in PostgreSQL called customers, customers has a table called CustomerInfo. CustomerInfo contains 3 colunms ID, Name and address. I would like to write a bash script to get the information from the CustomerInfo table but i am not sure how to access the individual rows once i have the results of the query. Here is the script i have written:

#!/bin/bash  

results=`psql -d customers -c "select * from CustomerInfo where name = 'Dave'"`

echo $results['name']

The query runs correctly and returns the correct results but the echo command will just print everything in results. I know this is not the correct way of doing this, does anyone know of a way to get the query results as an array, or would i just have to write my own function for parsing the results?

Thanks!

share|improve this question
1  
The effort needed to do that sort of thing with bash is better spent learning Perl basics. –  Daniel Vérité Dec 2 '13 at 12:38
    
Before trying to write anything yourself you have to realize what you are doing here: Executing a command and storing its output(text) in a variable. Therefore you would need to parse and disassemble that text in order to make this thing work. –  mistapink Dec 20 '13 at 7:43

3 Answers 3

You can store your results into an array and loop through it using a while loop.

psql -d customers -c "select * from CustomerInfo where name = 'Dave'"
| while read -a Record ; do
    # ${Record[0]} is your ID field
    # ${Record[1]} is your Name field
    # ${Record[2]} is your address field
done
share|improve this answer

You can't. You have to write your own function for paring the query results. Backtick( ` ) will execute the command and returns the output. In your case, results will have output of your query.

share|improve this answer

If I were tasked with doing this (really, Perl is better, take the advice of @daniel-verite), here is what I would do.

  1. Get a list of column names by piping the initial results through head
  2. Create a function which parses the rest using awk into a useful format.
  3. sed or awk to extract the relevant information from a row.

Now, the above assumes no embedded newlines (which would complicate things)

This amount of effort is anything but trivial. You really are better off learning Perl for a task like this.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.