The standard cp command does not provide an option to exclude specific subdirectories during a copy. If you try something like:
cp -r source/ destination/
it will copy everything inside source/, including any subdirectories you might want to omit.
To work around this limitation, you have a couple of good alternatives:
1. Use rsync (Recommended)
rsync is a powerful file-copying tool that includes an --exclude option.
For example, to copy the contents of source/ to destination/ while excluding the subdirectory dir-to-exclude, run:
rsync -av --exclude='dir-to-exclude' source/ destination/
-a enables archive mode (copies recursively and preserves attributes).
-v enables verbose output (optional).
--exclude='dir-to-exclude' tells rsync to skip that directory.
2. Use find with cp
If you must use cp for some reason, you can combine it with find to selectively copy files and directories while excluding the one you don't want.
For example:
mkdir destination
cd source
find . -mindepth 1 -maxdepth 1 ! -name 'dir-to-exclude' -exec cp -r {} ../destination/ \;
-mindepth 1 avoids copying the current directory (.).
-maxdepth 1 restricts the search to the immediate contents of source/.
! -name 'dir-to-exclude' excludes the unwanted directory.
-exec cp -r {} ../destination/ \; copies each found item recursively.
Be cautious with this approach—it essentially issues a separate cp command for each item, and you should adjust paths as needed.
3. Use a tar Pipeline
Another approach is to use tar to archive the source while excluding the unwanted directory, then extract it at the destination:
cd source
tar --exclude='./dir-to-exclude' -cf - . | (cd ../destination && tar -xf -)
--exclude='./dir-to-exclude' excludes the specified directory.
- This creates a tar archive on the fly that is piped into a tar extraction.
Conclusion
While the cp command itself doesn’t support exclusion, using rsync (option 1) is often the simplest and most efficient solution for copying while excluding specific directories.