How should I glob for all hidden files?
Solution 1
You can use the following extglob
pattern:
.@(!(.|))
.
matches a literal.
at first@()
is aextglob
pattern, will match one of the patterns inside, as we have only one pattern inside it, it will pick that!(.|)
is anotherextglob
pattern (nested), which matches any file with no or one.
; As we have matched.
at start already, this whole pattern will match all files starting with.
except.
and..
.
extglob
is enabled on interactive sessions of bash
by default in Ubuntu. If not, enable it first:
shopt -s extglob
Example:
$ echo .@(!(.|))
.bar .foo .spam
Solution 2
In Bash use:
GLOBIGNORE=".:.."
to hide the .
and ..
directories. This also sets the dotglob
option: *
matches both hidden and non-hidden files.
You can also do:
shopt -s dotglob
Solution 3
You can use a find
command here. For example something like
find -type f -name ".*" -exec chmod 775 {} \;
This will find hidden files and change permissions
Edit to include the comment by @gerrit:
find -type f -maxdepth 1 -name ".*" -exec chmod 775 {} \;
This will limit the search top the current directory instead of searching recursively.
Zanna
Updated on September 18, 2022Comments
-
Zanna over 1 year
I want to carry out some action (say
chown
) on all the hidden files in a directory.I know that this
.*
is not a good idea because it will also find the current.
and parent..
directories (I know thatrm
will fail to operate on.
and..
but other commands, includingchown
andchmod
, will happily take effect)But all my hidden files have different names!
How should I glob for all hidden files while excluding
.
and..
? -
Zanna over 7 yearsThis is clearly an awesome thing I need to learn about! Thank you for teaching
-
heemayl over 7 years@Zanna Glad i could help :)
-
Kyle Strand over 7 yearsWhat is the purpose of the
@()
? Simple.!(.|)
seems to work identically. -
Paddy Landau about 7 yearsI know that this is old, but I have the same question as @KyleStrand. In my tests,
!(.|)
works the same. Is there any purpose behind@()
in this context? -
datacarl almost 5 yearsIs the bang character a negation? It is not mentioned, and reading your explanation, I get the impression, that the pattern matches dot and doubledot, but you clearly describe files which match a starting dot, except just those two.
-
jcgoble3 over 2 yearsIMO this is better than the accepted answer. Easier to remember, infinitely more intuitive, and able to be stuffed into
.bashrc
to make it permanent if one so wishes (I know I almost never want*
to mean "non-dotfiles only").