I bet your loop is part of a pipeline
seq 5 | while read num; do x+=$num; done; echo $x
# expect "12345", actually see ""
In bash, when you construct a pipeline, it spawns subshells for all the parts. When the subshell exits, any variables you modify within it are destroyed too.
You have to code more carefully to ensure you use the variable in the same shell where you modify it.
This example echoes the var in the same subshell:
$ seq 5 | { while read num; do x+=$num; done; echo $x; }
12345
This example uses process substitution so the loop runs in the current shell
$ while read num; do x+=$num; done < <(seq 5)
$ echo $x
12345
variable="$variable$variable"
? I'll bet it's more portable than+=
. – Joseph R. Dec 17 '13 at 0:02