2

I try the code below to store the command output in an array but the array elements cannot be printed after the "while loop" I mean in the last line of my code is there any problem in my code?

#! /bin/bash

ls -a | while read line

do
    array[$i]="$line "  

        echo ${array[ $i ]}
        ((i++))
done

echo ${array[@]}  <------------
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    What do you mean by _the array elements cannot be printed after the "while loop"_? You got an error? No error, but nothing got printed? – jimm-cl Mar 27 '14 at 04:56

1 Answers1

2

The problem is that you add the elements in a subshell. To elaborate:

command1 | command2

causes command2 to be executed in a subshell, which is a separate execution environment. This implies that the variables set in command2 are not available to the current shell, whose execution environment is not affected. You could instead use process substitution to achieve the same:

while read line; do
 ...
done < <(ls -l)

Please note that parsing ls is not recommended; try using find instead.

mklement0
  • 382,024
  • 64
  • 607
  • 775
devnull
  • 118,548
  • 33
  • 236
  • 227