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[@]}  <------------
1
  • 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? Commented Mar 27, 2014 at 4:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot, i work for me. actually, i don't know it will work seperately
Good answer; for the sake of completeness: command1 is also executed in a subshell.
But Process Substitution is only working with bash and not sh (POSIX), unfortunately.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.