Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the .* wildcard in bash but exclude the parent directory (..)?

Tags:

bash

wildcard

There are often times that I want to execute a command on all files (including hidden files) in a directory. When I try using

chmod g+w * .* 

it changes the permissions on all the files I want (in the directory) and all the files in the parent directory (that I want left alone).

Is there a wildcard that does the right thing or do I need to start using find?

like image 323
Allan Avatar asked May 26 '10 04:05

Allan


2 Answers

You will need two glob patterns to cover all the potential “dot files”: .[^.]* and ..?*.

The first matches all directory entries with two or more characters where the first character is a dot and the second character is not a dot. The second picks up entries with three or more characters that start with .. (this excludes .. because it only has two characters and starts with a ., but includes (unlikely) entries like ..foo).

chmod g+w .[^.]* ..?* 

This should work well in most all shells and is suitable for scripts.


For regular interactive use, the patterns may be too difficult to remember. For those cases, your shell might have a more convenient way to skip . and ... zsh always excludes . and .. from patterns like .*. With bash, you have to use the GLOBIGNORE shell variable.

# bash GLOBIGNORE=.:.. echo .* 

You might consider setting GLOBIGNORE in one of your bash customization files (e.g. .bash_profile/.bash_login or .bashrc). Beware, however, becoming accustomed to this customization if you often use other environments. If you run a command like chmod g+w .* in an environment that is missing your customization, then you will unexpectedly end up including . and .. in your command.

Additionally, you can configure the shells to include “dot files” in patterns that do not start with an explicit dot (e.g. *).

# zsh setopt glob_dots  # bash shopt -s dotglob   # show all files, even “dot files” echo * 
like image 141
Chris Johnsen Avatar answered Sep 25 '22 22:09

Chris Johnsen


Usually I would just use . .[a-zA-Z0-9]* since my file names tend to follow certain rules, but that won't catch all possible cases.

You can use:

chmod g+w $(ls -1a | grep -v '^..$') 

which will basically list all the files and directories, strip out the parent directory then process the rest. Beware of spaces in file names though, it'll treat them as separate files.

Of course, if you just want to do files, you can use:

find . -maxdepth 0 -type f -exec chmod g+w {} ';' 

or, yet another solution, which should do all files and directories except the .. one:

for i in * .* ; do if [[ ${i} != ".." ]] ; then chmod g+w "$i"; fi done 

but now you're getting into territory where scripts or aliases may be necessary.

like image 45
paxdiablo Avatar answered Sep 21 '22 22:09

paxdiablo