Since your while loop is in the pipeline, all variable assignments in the body of the loop are local to the subshell in which the loop is executed. (I believe that ksh does not run the command in a subshell, so you have a problem in bash .) Do this instead:
while read line do array[i]="$line" echo "array[$i] = ${array[i]}" let i++ done < junk.txt
Rarely, if ever, do you want to use cat to join one file with another command; use input redirection instead.
UPDATE: since you need to execute the command from the command line and not the file, another option (if available) is to replace the process:
while read line; do ... done < <( command args ... )
If process substitution is not available, you will need to output to a temporary file and redirect input from this file.
If you are using bash 4.2 or later, you can execute these two commands before your loop, and the original pipe-in-loop will work, since the while loop is the last command in the pipeline.
set +m
UPDATE 2: This is a no-loop solution based on user comment1596414
array[0]=hello IFS=$'\n' array+=( $(command) )
The output of your command is broken down into words based solely on newline characters (so that each line is a separate word) and adds the resulting array of lines to the slot in the original. This is very good if you use a loop only to build an array. It can also be modified to accommodate a small amount of processing on each line, vaguely similar to understanding a Python list.
source share