What is the difference between cp -r and cp -a?
cp -r copies directories recursively but new files get fresh timestamps, your ownership and default permissions. cp -a (archive) also preserves permissions, ownership, timestamps and symlinks, so the copy matches the original as closely as possible.
Explain it simply
Photocopying a file and getting a fresh date on it is cp -r. Getting a perfect clone with the same date, owner and markings is cp -a.
-r (or -R) is only about recursion: go into folders and copy everything. The copies are owned by whoever ran the command, get the current time, and permissions are filtered by the umask.
-a is shorthand for -dR --preserve=all. It copies recursively, keeps symlinks as symlinks instead of copying their targets, and preserves mode, ownership (when run as root), timestamps and extended attributes. Use it for backups and for copying a web root or config directory.
Example
cp -r site/ copy1/ # new timestamps, owned by you
cp -a site/ copy2/ # same timestamps, links and modes
ls -l --time-style=long-iso site/index.html copy2/site/index.htmlNote the trailing slash on the source: cp -a site copy2 creates copy2 as a copy; if copy2 already exists it creates copy2/site.
What to say in the interview
"-r just recurses; the copy gets new timestamps and my ownership. -a is archive mode: it recurses and preserves permissions, timestamps, symlinks and, as root, ownership. I use -a for backups and for copying config trees."
Common mistakes
- Using cp -r for a backup and losing permissions and symlinks.