Link to home
Start Free TrialLog in
Avatar of dongjinkim
dongjinkimFlag for Canada

asked on

How to load standard output into an array using bash?

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:

INDEX=0
psql -c "select * from some_table' |
while read LINE
do
  DATA[$INDEX]=$LINE
  (( INDEX = INDEX + 1 ))
done

# 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)
SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dongjinkim

ASKER

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?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial