1

i have an issue with my bash script

t='Hostname\cfg;'

echo "Header" > $DST

for i in *
do
        t="$i;"
        egrep -v "(^$|^#)" $IPLIST | while read ii
        do  
                if grep -q "$ii" $i
                then
                        t=$t"y;"
                else
                        t=$t"n;"
                fi  
echo "$t"
        done

echo "x$t"

        n=$(($n + 1))
        echo "$n"

        #echo "$ii;$t" # >> $DST
        #t=""
done

Produces the following output:

h0010001.conf;y;
h0010001.conf;y;y;
<ommited>
h0010001.conf;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;y;n;n;y;y;y;y;y;y;y;y;y;y;y;y;n;y;y;y;y;y;y;n;y;y;y;y;y;y;y;y;y;n;n;
xh0010001.conf;

So for some reason the t Variable is empty after the inner loop has completed. What I want to achieve is, to write t - after the second loop into a file.

1
  • 1
    Commands in a pipeline are executed in a subshell, so variable assignments don't affect the original shell. Commented Oct 29, 2013 at 10:07

1 Answer 1

1

@Barmar was spot on. Here's a typical workaround.

Change the while loop to run in the parent shell:

while read ii
    do  
            if grep -q "$ii" $i
            then
                    t=$t"y;"
            else
                    t=$t"n;"
            fi  
            echo "$t"
    done < <(egrep -v "(^$|^#)" $IPLIST)
Sign up to request clarification or add additional context in comments.

4 Comments

Though, the external egrep is completely useless.
@gniourf_gniourf that's immaterial to the question, but yes, there are many things I'd write different here
In fact it is somehow related, because if the OP hadn't used this egrep and had filtered directly using globs, the question would have never arised!
He's asking about the reason why his variable "didn't stick". He could avoid having the problem in many many (unrelated) ways.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.