Problem with variable value

[LEFT]Can anyone help me?...I don't know why the second 'echo $contador' always shows 0 (zero):

  1 #!/bin/bash
  2 contador=0
  3 while read linea
  4 do
  5    echo
  6    echo "$linea" | while IFS="" read -n 1 caracter
  7    do
  8       contador=$((${contador}+1))
  9       echo $contador
 10    done
 11    echo $linea
 12    echo $contador
 13    
 14 done < leerfichero.sh

:confused:
[/LEFT]

can you provide with some information ?

Of course.
When executed, the output (echo in line 9) is:
1
2
3
....until the length of the first line of the file "leerarchivo.sh"
but..the 'echo' in line 12 prints 0.
This is the result.

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
0

I would like the last '0' were 12! I don't understand why..

Because

  6 ...while IFS="" read -n 1 caracter
  7    do
  8       contador=$((${contador}+1))
  9       echo $contador
 10    done

is executing in a subshell. $contador inside that loop and $contador outside of it have nothing to do with each other.

pipes invokes subshells.

echo "$linea" | while IFS="" read -n 1 caracter

the while loop is starting in a sub shell and all the processing (until done) is processing in the same shell. when the loops finishes, the execution returns to the parent shell and the modified value of contador left in the older (subshell).

what you are getting (zero) is the value of the variable in the parent shell.

you can force the command to execute in the same shell with (...).

try:

contador=0
while read linea
do
    echo ""
    echo "$linea" | (while IFS="" read -n 1 caracter
    do
       contador=$((${contador}+1))
       echo $contador
    done
    echo $linea
    echo $contador )
done < leerfichero.sh

Thank you very much
I'm a newbie in shell scripting!