Thursday, February 1

bash globbing and dot-files

Found a nifty little feature in bash.

Globbing is expanding file pattterns, like when you typ "ls -l file*" in bash it is not ls that does the file matching and filtering. bash will glob ("expand") the file list file* and ls will get all the files as arguments.
Now, per default bash doesn't glob dot-files. If I do "ls *" I will not get .bashrc and .bash_profile etc. Luckily it is easy to change this behavior. Set the bash option dotglob to enabled and it works!
Example:

[hlinden@spinner testdir]$ ls -Al
total 0
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 .dotfile1
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 .dotfile2
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 file1
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 file2
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 file3

[hlinden@spinner testdir]$ echo *
file1 file2 file3
[hlinden@spinner testdir]$ shopt -s dotglob
[hlinden@spinner testdir]$ echo *
.dotfile1 .dotfile2 file1 file2 file3
[hlinden@spinner testdir]$
Just put shopt -s dotglob in your .bashrc file or in a global /etc/profile.d file.
Another quite nice globbing feature is to have case insensitive globbing.
Check this out:
[hlinden@spinner testdir]$ shopt -s nocaseglob
[hlinden@spinner testdir]$ ls -l F*1
-rw-rw-r-- 1 hlinden hlinden 0 Feb 1 2007 file1
[hlinden@spinner testdir]$

7 comments:

Don said...

Wouldn't it be easier to just use -a when you want to see dot-files? I don't know if I'd want to see dot-files all of the time.

Hampus said...

-A is the equivalent of -a but does not show "." and "..".
And I agree, I don't want to see dot-files all the time either. But sometimes I want * to mean everything, perhaps in a scripts.
Even with dotglob active, "ls -l" with not show dot-files, only wild card expansion will include dot-files.

Anonymous said...

I just ran into the case-insensitive file glob "feature". It is a broken shell in my opinion. I'm not trying to find out how to turn it off so it works like every other shell on the planet.

Anonymous said...

I just used the dotglob option to run
du -sm * |sort -g
and see all files/dirs in my list of biggest dirs

Ladadadada said...

You can easily include dot-files when globbing by using an extra parameter:

ls -l * .*

(Note the space between the * and the .*)

Or just the dot-files with:

ls -l .*

Anonymous said...

I have been looking for some info about bash globbing and dot-files, and wow I have no idea that in the web were so many blogs related to generic viagra, but anyways, thanks for sharing your inputs and have a nice day.

Lars said...

Much spam here ...

spam, spam, spam, spam, SPAM, SPAM, SPAM, SPAM ...