Reputation: 753
Hi guys sorry for the awkward title but I think it is a bit subtle to describe. So here is my problem, I want to keep a count (i) in a while loop which reads input from awk, and then print the value of i after the loop. However i becomes back to zero after the loop. Below is a simplified version of my program, in reality I also did some string matching inside the loop so that some lines are skipped and i does not increment.
I have tried to remove awk and do another ordinary while loop and i's value is kept after the loop, therefore I believe it's not due to some syntax error.
Any idea is great appreciated!
#!/bin/bash
arr=();
i=0;
awk -F '{print $1}' SOMEFILE | while read var
do
echo $var;
arr[i]=$var;
i=$((i+1));
echo $i;
done
echo $i;
Upvotes: 0
Views: 2081
Reputation: 212198
Because the while loop is in a pipeline, it is running as a subprocess, and the value of i is local to that subprocess. There are several ways to keep the value; use a named pipe instead of running while in a pipeline, use process substitution, or use an interpolating heredoc. Here's an example of the latter:
while read var; do ... done << EOF
$( awk ... )
EOF
Upvotes: 2