Question

I understand that the wildcard * (by itself) will expand in such a way that it means "all non-hidden files in the current folder" with hidden files being those prefixed by a period.

There are two use cases that I would think are useful, but I don't know how to properly do:

  1. How can you glob for... "All files in the current folder, including hidden files, but not including . or .."?

  2. How can you glob for... "All hidden files (and only hidden files) in the current folder, but not including . or .."?

Was it helpful?

Solution

To expand on paviums answer and answer the second part of your question, all files except . and .. could be specified like this:

{.[!.]*,*}

Depending on your exact use case it might be better to set the dotglob shell option, so that bash includes dotfiles in expansions of * by default:

$ shopt -s dotglob
$ echo *
.tst

OTHER TIPS

The Bash Cookbook suggests a solution to your 2nd requirement.

.[!.]*

as a way of specifying 'dot files' but avoiding . and ..

Of course, ls has the -A option, but that's not globbing.

To meet your first case:

echo {.,}[^.]*

or

echo {.,}[!.]*

Edit:

This one seems to get everything, but is shorter than ephemient's

echo {.*,}[^.]*

Combining sth and pavium answers

# dot files but avoiding . and ..
.[!.]*

# all files but avoiding . and .. 
{.[!.]*,*}

By "all files" and "all hidden files" do you mean files-only, or do you mean both files and directories? Globbing operates on names irrespective of it belonging to a file or a directory. The other folks give good answers for using globbing to find hidden vs non-hidden names, but you may want to turn to the find command as an easier alternative that can distinguish between the types.

To find "All files in the current folder, including hidden files, but not including . or ..":

find . -type f

To find "All files and directories in the current folder, including hidden files, but not including . or ..":

find . ! -name .

To find "All hidden files (and only hidden files) in the current folder, but not including . or ..":

find . -name '.*' -type f

To find "All hidden files and directories (and only hidden files and directories) in the current folder, but not including . or ..":

find . -name '.*' ! -name .

Note that by default find will recurse through subdirectories, too, so if you want to limit it to only the current directory you can use:

find . -maxdepth 1 -type f

So, even though this is old - without using shopt, this doesn't seem to have been answered fully. But, expanding on what has been given as answers so far, these work for me:

1:

{*,.[!.]*,..?*}

2:

{.[!.]*,..?*}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top