Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do you exclude a folder when performing file operations i.e. cp etc.

I would currently use the wild card * to apply file operation to all, but I need to exclude one single folder.

The command I'm actually wanting to use is chown to change the owner of all the files in a directory but I need to exclude one sub directory.

share|improve this question
Cross-posted here:… – Dennis Williamson Jan 14 '10 at 16:27
up vote 7 down vote accepted

Inverse Globbing:
You want an inverse match of a glob, I would do it like the following:

You can do an inverse match with a newer bash if you enable extended globbing. For example, to match everything that doesn't have foo or bar in the name:

shopt -s extglob
echo !(*foo*|*bar*)

Or just everything that doesn't have foo:

shopt -s extglob
echo !(*foo*)

You could also use find (this is the most robust option I think), and use ! to negate a match, and then run the command with xargs -0:

find . ! -iname 'foo' -print0 | xargs -0 echo

Just mv the folder somewhere else, do what you need to do, and put it back :-)

share|improve this answer

rsync -arv --exclude={files} {Destination}

share|improve this answer

the find solution spawns one chown process per file, sometimes that can be a problem. This solution spawns only one perl process:

find . | perl -nle "chown($(id -u user), $(id -g group), \$_) unless m/foo/"
share|improve this answer
No, the find solution doesn't do this if you use it with xargs. Your script would also not only exclude the directory /foo, but also the file /bar/foo and the directory /foobar. – Sven Dec 16 '14 at 3:44
Yes, you have to adjust the regular expression as needed. Might I also point out that glob based solutions will also have the problem of matching /foobar – Antonio Dolcetta Feb 16 '15 at 8:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.