MacOS

I stumbled on this while reading through some notes about git worktrees, and found it to be a pretty handy trick.

The version of cp on MacOS supports -c for creating copy-on-write copies of a file. E.g., this command would copy a node_modules folder to another directory:

/bin/cp -Rc project1/node_modules project2/

And then if you make any changes to the files in project2/, they will not be reflected back to the project1/ directory.

This also uses /bin/cp since if you install coreutils, the version of cp there has a different meaning for -c.

Note: If you do want changes to reflect, you probably want symlinks or hardlinks instead.

What about Linux?

Linux has had a similar feature in coreutils cp for a while:

--reflink[=WHEN]
control clone/CoW copies. See below
...
When --reflink[=always] is specified, perform a lightweight copy,
where the data blocks are copied only when modified. If this is
not possible the copy fails, or if --reflink=auto is specified,
fall back to a standard copy. Use --reflink=never to ensure a
standard copy is performed.

So on most linux systems, you can do cp --reflink=auto and it will use copy-on-write if supported by the filesystem.