0

I am experiencing a weird (or at least unexpected) behavior of BASH (v5.2.32) local variables in a while loop.

The "distilled" code (my actual use case is rather more complex, though) that reproduces the behavior is:

function xxtest () {
  local l n
  seq 0 9 |  while read n; do
    l="$l $n"
    echo "n='$n'"
    echo "l='$l'"
  done
  echo "FINAL l='$l'"
}

This is the output I get:

$ xxtest 
n='0'
l=' 0'
n='1'
l=' 0 1'
n='2'
l=' 0 1 2'
n='3'
l=' 0 1 2 3'
n='4'
l=' 0 1 2 3 4'
n='5'
l=' 0 1 2 3 4 5'
n='6'
l=' 0 1 2 3 4 5 6'
n='7'
l=' 0 1 2 3 4 5 6 7'
n='8'
l=' 0 1 2 3 4 5 6 7 8'
n='9'
l=' 0 1 2 3 4 5 6 7 8 9'
FINAL l=''

I can see the l variable "growing" as expected with the leading blank.

After the done keyword and right before the function returns that l variable becomes empty.

Nothing changes when I remove the line with the local variable declaration, thus making those variables global!

I don't think this is a bug. Nonetheless I am not able to explain the behavior.

Any hint?

EnzoR
  • 1,747

0 Answers0