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/*
do
echo "$file"
var=1
done
That's it! Just let /tmp/*
expand to provide all the contents in the /tmp
directory.
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
r=(/tmp/*)
And then count the elements in the array:
echo ${#r[@]}
Note I used shopt -s nullblog
to prevent /tmp/*
to expand to the literal string /tmp/*
if nothing matches this pattern.
while
/subshell/pipe question! See http://mywiki.wooledge.org/BashFAQ/024 And http://unix.stackexchange.com/questions/9954/why-is-my-variable-being-localized-in-one-while-read-loop-but-not-in-another/9994#9994 And http://unix.stackexchange.com/questions/21743/piping-for-loop-output-prevents-local-variable-modification ...among others. – Mike S May 20 '15 at 18:08