How should I glob for all hidden files?

5,735

Solution 1

You can use the following extglob pattern:

.@(!(.|))
  • . matches a literal . at first

  • @() is a extglob pattern, will match one of the patterns inside, as we have only one pattern inside it, it will pick that

  • !(.|) is another extglob 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

Gilles :)

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.

Share:
5,735
Zanna
Author by

Zanna

Updated on September 18, 2022

Comments

  • Zanna
    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 that rm will fail to operate on . and .. but other commands, including chown and chmod, will happily take effect)

    But all my hidden files have different names!

    How should I glob for all hidden files while excluding . and .. ?

  • Zanna
    Zanna over 7 years
    This is clearly an awesome thing I need to learn about! Thank you for teaching
  • heemayl
    heemayl over 7 years
    @Zanna Glad i could help :)
  • Kyle Strand
    Kyle Strand over 7 years
    What is the purpose of the @()? Simple .!(.|) seems to work identically.
  • Paddy Landau
    Paddy Landau about 7 years
    I 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
    datacarl almost 5 years
    Is 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
    jcgoble3 over 2 years
    IMO 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").