The reason why your variable value is not kept has already been explained by the other good answer. If you feel like, you can read an interesting article about this topic in I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?.
I just want to show another way to loop through your files, so that you don't parse
ls at all:
for file in /tmp/*
That's it! Just let
/tmp/* expand to provide all the contents in the
I guess your script was just some dummy code, not the real code. But if you happen to be checking whether
/tmp contains some values or not, you can also say:
shopt -s nullglob
And then count the elements in the array:
Note I used
shopt -s nullblog to prevent
/tmp/* to expand to the literal string
/tmp/* if nothing matches this pattern.