I need to iterate through every file inside a directory. One common way I saw was using the for loop that begins with for file in *; do
. However, I realized that it does not include hidden files (files that begin with a "."). The other obvious way is then do something like
for file in `ls -a`; do
However, iterating over ls
is a bad idea because spaces in file names mess everything up. What would be the proper way to iterate through a directory and also get all the hidden files?
for file in dir/.* dir/*; do
– stack smasher Oct 16 '14 at 20:46.*
matches.
and..
(except in zsh).*
stays*
if there is no matching file.shopt -s gotglob
is only in bash. – Gilles 'SO- stop being evil' Oct 16 '14 at 23:23zsh: no matches found: .*
when I run the command(s) in this answer. Why would this happen? ls on the directory shows the files. – Niyaz Oct 10 '17 at 18:57zsh
return error if some pattern no matches. To prevent that runsetopt nullglob
which will turn off this feature globally, or add qualifier(N)
after the glob star, i.e.:for file in /path/{.,}*(N); do echo "$file"; done
. – jimmij Oct 10 '17 at 22:13