You need to
cd out of each subdirectory before trying the next one. Inserting...
at the end of the loop would fix this for the subdirectories, but breaks when you do it in the top directory first. A
cd .. from there will take you up another level, so the other directories aren't visible any more.
You can address all of this by saving the top directory in a variable, and
cd to there each time:
for X in "$PWD" * ;
if [ -d "$X" ] ;
echo "$files" >> filesNames.txt
You might also want to change
>, if you don't want to keep all the results from previous runs.