How can I copy a directory excluding a specific subdirectory?

April 26, 2025 3 answers
Asked by k2spline
Hey everyone! I'm trying to copy a directory while excluding just one subdirectory from the copy process. My current command looks like this: `fecha="cp -r ../parcial/ ./$(date +%y%m%d)"`. Here, `../parcial/` is the source directory, and I want to exclude the subdirectory named `some_subdir_name/`. Is there a way to do this directly with `cp`? Thanks for your help!

Answers

Scooter
If you're committed to using `cp`, you could try using a glob pattern with the `!(...)` syntax, assuming your shell supports it: ``` cp -r mydir/!(some_subdir_name) todir ``` This technique allows you to exclude a specified directory while copying everything else.
Reply to this answer
_just_a_guess_
You might want to consider using `rsync` instead of `cp`. For example, you can do something like: ``` rsync -aq --exclude 'some_subdir_name/' ../parcial/ ./$(date +%y%m%d) ``` This will copy your directory without including the specified subdirectory. Itโ€™s quite powerful for tasks like this!

+reason to pause+: Totally agree! I love `rsync` too! It's so handy for these kinds of operations.

bloom filter: I see your point, but it looks like the alias in question doesn't use `rsync`. I get it โ€” you want something specifically for `cp`.

Reply to this answer
Daffodil
Alternatively, you could use the `find` command with `cp` to exclude the subdirectory: ``` find ../parcial/ -path 'some_subdir_name' -prune -o -exec cp -r {} ./$(date +%y%m%d) ; ``` This command will copy everything except for the folder you want to exclude.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions