user2677587
user2677587

Reputation: 1

non working array in bash

Can anyone helps with my problem with arrays in BASH? I have this code:

i=1
cat test.txt | while read LINE; do
    string=$(echo $LINE | sed -e 's/\(^[^=]*\):[^=]*$/\1 /')
    log_content[$i]="$string"
    echo -e "\t $i) ${log_content[$i]}"
    i=$(expr $i + 1)
done
pattern=$(echo ${log_content[1]})   - this is zero :(

When I use ksh instead of bash everything works fine. When I use BASH (which aj want to use because of many others purposes), variable "pattern" desnt have any value. Even when I want to show whole content of "log_content" array, there is nothing. Thanks a lot.

Upvotes: 0

Views: 40

Answers (1)

Yorik.sar
Yorik.sar

Reputation: 5917

Your log_content variable is being filled inside a subshell that runs your while loop so the value of log_content variable in the outer shell never changes.

To mitigate this you should avoid creation of subshell by using input redirection instead of pipe:

while read LINE; do
  ...
done < test.txt

This should work.

Upvotes: 1

Related Questions