LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [BASH] non-empty variable before loop end, is empty after exiting loop (https://www.linuxquestions.org/questions/programming-9/%5Bbash%5D-non-empty-variable-before-loop-end-is-empty-after-exiting-loop-828618/)

aitor 08-26-2010 09:14 AM

[BASH] non-empty variable before loop end, is empty after exiting loop
 
Hi fellows:

I'm having a quite disturbing trouble with this simple script:

Code:

#!/bin/bash

DIR_HTML_UTF=/home/GGG_index/htmlUtf
vid=""

find $DIR_HTML_UTF -type f -name "*html" | sed 's/[^0-9]//g' | sort -u | while read vid; do
        echo $vid
        vids="$vids,$vid"
        echo "  >> ${vids:1}"
done

echo "=== $vids ==="

And the result of the script is:

Code:

101993
  >> 101993
150115
  >> 101993,150115
150188
  >> 101993,150115,150188
32416
  >> 101993,150115,150188,32416
93939
  >> 101993,150115,150188,32416,93939
===  ===

I can't understand why $vids is empty after de loop. It's just too weird, isn't it?

I'm using a Ubuntu 10.04 64bits box.

Thx!

David the H. 08-26-2010 09:30 AM

It's a simple and common mistake. You used a pipe to feed the output of find into the while loop, which means it runs in a subshell. The subshell can't affect the parent process, so the settings are lost when it exits.

You need to reposition the input as a redirect instead. Something like this (untested):
Code:

while read vid; do
        echo $vid
        vids="$vids,$vid"
        echo "  >> ${vids:1}"
done <<<"$(find $DIR_HTML_UTF -type f -name "*html" | sed 's/[^0-9]//g' | sort -u )"

It's #8 on this list, which includes a link to a more detailed explanation.

http://mywiki.wooledge.org/BashPitfalls

aitor 08-26-2010 09:57 AM

Thanks a lot, now i see. I was expecting something like that, so i tried to "export" the variable in some way.

I searched for the answer at LQ, but was sort of difficult to figure out how to search such a problem (loop + variable + empty ¿?). Sorry for reiteration.


All times are GMT -5. The time now is 10:38 AM.