Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script & PostgreSQL: How to access column values returned from SELECT statement

I have a database in PostgreSQL called customers, customers has a table called CustomerInfo. CustomerInfo contains 3 columns 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!

like image 548
Robbie Torrens Avatar asked Dec 02 '13 12:12

Robbie Torrens


People also ask

What is in a bash script?

A Bash script is a text file containing a series of commands. Any command that can be executed in the terminal can be put into a Bash script. Any series of commands to be executed in the terminal can be written in a text file, in that order, as a Bash script.

What is Z in bash script?

Use the -z Flag in Bash The test command can be used with a parameter. The -z flag is a parameter that checks if the length of a variable is zero and returns true if it is zero. In the example below, the -z flag is used with the test command, and it is tested whether the given string is empty. Bash.

What is a bash script vs shell script?

Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems. sh provides some built-in commands. bash is a superset of sh.


1 Answers

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
like image 116
bckim Avatar answered Nov 15 '22 06:11

bckim