0
#!/bin/bash

read()
{
    count=0
    cat localfile |
    while read line
    do
        FILE[$((count += 1))]="$line"
    done
}

read
for((i=0;i<${#FILE[@]});i++)
do
    echo ${FILE[i]}
done

The result of echo is whole blank. Is there any way to get the FILE array?

1 Answers1

0

You posted this under ash, the Almquist shell, but you are using bash, the Bourne-Again SHell.

One problem is the pipe. When you run a pipe in bash, each side runs in its own sub-shell, and any variables are local to it. The correct mechanism is to redirect into the loop.

Another problem is that your function is called read, which is a shell-builtin (you use it!). A good idea is to use a naming convention, like an f_ prefix, so you don't get these name collisions.

Another issue you have is that the syntax of your second for loop is wrong in several ways. Here is a corrected version:

#!/bin/bash

f_read()
{
    count=0
    while read line
    do
        FILE[$((count += 1))]="$line"
    done < localfile
}

f_read
for ((i=0;i<${#FILE[@]};i++))
do
    echo ${FILE[i]}
done
cdarke
  • 37,606
  • 5
  • 69
  • 77