I have a variable into a do loop. I append its content to a file, but I want to append it to itself so I could use it to do other stuff like sending mail.

I tried variable+=$variable but it didn't work.

I want to have access to the variable outside the do...done

closed as unclear what you're asking by Gilles, jasonwryan, slm, rahmu, Chris Down Dec 17 '13 at 3:20

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


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; }

This example uses process substitution so the loop runs in the current shell

$ while read num; do x+=$num; done < <(seq 5)
$ echo $x

If these are just strings you can append like this:


$ somevar="a string"
$ echo $somevar
a string

$ somevar="$somevar$somevar"

$ echo $somevar
a stringa string


You can use the same technique in a for loop in Bash.

$ a="0"; for i in $(seq 3); do a="$a$i"; echo "$i | $a"; done
1 | 01
2 | 012
3 | 0123

Not the answer you're looking for? Browse other questions tagged or ask your own question.