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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With