0

I have postgresql, in that I have a table with 10 records, I want the 10 records in 10 local variables shell script.

I tried with following way, but it will store all the records in list123[0] variable not on list123[1]...list123[9].

declare -a list123
list123=( "$(psql -t -h 10.100.0.1 -U prasad statistics -c "select command from jobhandler.config_info where conf_name like '%stager%'")" )

I want each record in corresponding list123[0-9].

1

I'm not certain I'm answering your question. Do you want an array of 10 strings as a local variable, or 10 shell variables, each containing a string?

The latter requires a weird trick:

#!/bin/bash

COUNTER=1
eval $(psql -t -h 10.100.0.1 -U prasad statistics -c "select command from jobhandler.config_info where conf_name like '%stager%'" |
while read VAR
do
    echo "list123$COUNTER='$VAR'"
    ((COUNTER = COUNTER + 1))
done)

echo list1231="$list1231"
echo list1232="$list1232"

This variant ends up setting shell variables named "list1231", "list1232", "list1233" ..., it does not set different elements of an array shell variable named "list123"

2

The problem is caused by the double-quotes you've placed around the $() command substitution. That turns the entire output into a single multi-line string.

Try:

declare -a list123
list123=( $(psql -t -h 10.100.0.1 -U prasad statistics -c "select command from jobhandler.config_info where conf_name like '%stager%'") )

I don't have your table, but i tested with a simple id,name,dob table on my system:

$ list123=($(psql -t -c 'select dob from newtable'))
$ set | grep list123
list123=([0]="1967-03-07" [1]="1964-08-07" [2]="1992-10-19" [3]="1964-12-18" [4]="1945-12-26")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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