DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
0 votes

I want to copy everything, minus a few files and a folder. Is there an "exclude" option? Like cp -R --exclude ... <source> <destination>


2 Answers

+2 votes
Best answer

cp has no exclude option. You can either:

  • Use rsync with --exclude like wjazz suggest.
  • Use your shell's special glob operation if it has one.

Both Bash and Zsh have special patterns to match everything except X, but they require enabling extended globbing first.


In an interactive shell, extended globbing is enabled by default on most distributions. However, in an interpreted script it's not, so first it has to be enabled with:

shopt -s extglob

Then, use the !() syntax to match everything except what's inside the parentheses:

# "file.txt" is the file we want to exclude
cp !(file.txt) destination

# multiple files can be excluded by using the pipe alternation
cp !(file1.txt|file2.txt) destination

See bash(1) manual page (section Pattern Matching) or (bash)Pattern Matching info page, for more matching operators.


Zsh doesn't enable extended globs by default in neither interactive nor interpreted shells. To enable it, use:


The syntax in Zsh is to simply a prefix the pattern with ^:

# "file.txt" is the file we want to exclude
cp ^file.txt destination

# multiple files can be excluded by using parentheses and pipe alternation
cp ^(file1.txt|file2.txt) destination

See zshexpn(1) manual page, section FILENAME GENERATION for more glob operations.

selected by
0 votes

You can use rsync, which has an --exclude option.


In other words the answer is that it is not possible with bare cp?

Contributions licensed under CC0