How to load standard output into an array using bash?

dongjinkim used Ask the Experts™
Hello experts,
I have 2 restrictions on a script I need to write.
I need to use bash shell.
I cannot generate temporary files due to permission settings on the file system.

Given those restrictions, is it possible for me to capture the standard output of a program (e.g. psql) and store each line in an array?
I know this is easily possible in korn shell, because I can simply use a pipe to direct the standard output into a loop that reads each line into the array:

psql -c "select * from some_table' |
while read LINE
  (( INDEX = INDEX + 1 ))

# the following line displays data in ksh but not bash
echo DATA=$DATA{*}

However, it seems that bash shell spawns a new shell every time a pipe is used. In this case, the while loop runs inside a different shell... the changes to the DATA array are lost once the while loop finishes, since the spawned shell is closed.

Does anyone have a solution for this problem?  (i.e. load each line of standard output into an array)
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
DATA=( `psql -c "select * from some_table` )
echo DATA=${DATA[*]}


Hi ozo,
Thanks for your response.
Your solution works fine as long as there is no white space within each line of output. The embedded white space is splitting up each line into multiple elements.
Is it possible to get around this white space issue?
$ ifs="$IFS"
$ export IFS="            <-- Press enter after typing the quote
> "
$ DATA=( `psql -c "select * from some_table` )
$ export IFS="$ifs"
$ echo DATA=${DATA[*]}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial