how to find hidden file

jojo picture jojo · Dec 19, 2010 · Viewed 22.3k times · Source

i have some files, they are named like this

.abc efg.txt 
.some other name has a dot in front.txt
......

and i want to do something like this

for i in `ls -a` ; do echo $i; done;

i expected the result should be

.abc efg.txt
.some other name has a dot in front.txt

but it turns out a buch of mess.. how can i get those hidden file???

thanks

Answer

Peter van der Heijden picture Peter van der Heijden · Dec 19, 2010

Instead of using ls use shell pattern matching:

for i in .* ; do echo $i; done;

If you want all files, hidden and normal do:

for i in * .* ; do echo $i; done;

(Note that this will als get you . and .., if you do not want those you would have to filter those out, also note that this approach fails if there are no (hidden) files, in that case you would also have to filter out * and .*)

If you want all files and do not mind using bash specific options, you could refine this by setting dotglob and nullglob. dotglob will make * also find hidden files (but not . and ..), nullglob will not return * if there are no matching files. So in this case you will not have to do any filtering:

shopt -s dotglob nullglob
for i in * ; do echo $i; done;