So I'm trying to read datafile into an array, with each line representing one variable in the array. I'm successful at first but somehow it keeps getting erased.
i=0
grep '.*' datafile | while read line
do
echo $i
array[$i]=$(echo $line)
echo ${array[1]} #printing array to make sure it's still there
(( i++ ))
done
echo ${array[1]} #isn't there anymore
Your script is relying on undefined behavior. If you want it to work as is, use ksh instead of bash. Bash made an implementation choice that break your logic.
In ksh this would work, but as others have noted one of the intricacies of bash is that the part after the pipe get run in a subshell. You do not need a grep statement and a pipe, you can use an if or case statement inside the loop to filter out empty lines.
If you still need to use a pipe into a while loop in bash you can do this:
i=0
grep '.*' datafile | {
while read line
do
echo $i
array[$i]=$(echo $line)
echo ${array[1]} #printing array to make sure it's still there
(( i++ ))
done
echo ${array[1]} #isn't there anymore
}
You can try this technique for reading the file into an array :
$ cat read_file.sh
i=0
while IFS= read line
do
set_array="${set_array}array[$i]='${line}';"
(( i++ ))
done < inputfile
eval ${set_array}
echo "array size=${#array[*]}"
for ((i=0; i<${#array[*]}; i++))
do
echo "array[$i]=${array[$i]}"
done
$ cat inputfile
First line
Line 2
Last line
$ ./read_file.sh
array size=3
array[0]=First line
array[1]=Line 2
array[2]=Last line
$