I have a postgres sql statement that is the following:
select age from students;
which gives me the entries:
Age
---
10
15
13
12
9
14
10
which is about 7 rows of data.
Now what I would like to do with this is use a shell script to create an array age[]. As a results age[1]=10, age[2]=15, age[3]=13, age [4]=12, age[5]=9, age[6]=14, age[7]=10.
Any ideas on how to create a shell script.
I have been able to do the following:
Unix_Array=$(psql -h $PSQL_HOST $PSQL_RDB $PSQL_USER << EOFF
BEGIN TRANSACTION;
select age from students;
END TRANSACTION;
\q
EOFF
)
echo $Unix_Array
Unix_Array gives me all the ages at once like this:
10
15
13
12
9
14
10
but I cannot for example parse Unix_Array into individual variables such Unix_Array[1]=10, Unix[2]=15 and so on like I described above. Any ideas?
First, the array values start from 0
and, there are several ways of doing this
for i in $(seq 0 $((${#age[@]} - 1)))
do
grade_${i}=$(psql -h $PSQL_HOST $PSQL_RDB $PSQL_USER << EOFF
BEGIN TRANSACTION;
select grade_level from characteristcs where age=${age[$i]};
END TRANSACTION
\q
EOFF
)
done
The above approach is costly as it required one DB Connection for each value of the array age.
Rather, you can go with the below approach and run all the details into grade array
for i in $(seq 0 $((${#age[@]} - 1)))
do
echo "select grade_level from characteristcs where age=${age[$i]}"
done > query.sql
grade=($(psql -h $PSQL_HOST $PSQL_RDB $PSQL_USER -a -f query.sql))