C.W.K.
Stream
Lesson 08 of 12 · published

cp, mv — Copying and Moving

~12 min · cp, mv, rsync

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

cp — copy with care

cp source dest copies one file. Common flags:

  • -r — recursive, for directories
  • -i — interactive, ask before overwrite
  • -n — never overwrite (silently skips)
  • -v — verbose, list each file copied
  • -p — preserve mode, ownership, mtime
  • -a (GNU) — archive: -rp plus symlinks etc.

Trailing slash matters: cp foo/ bar copies contents of foo into bar (if bar exists). Without the slash, cp foo bar renames or creates a child. Always test on a throwaway directory first.

mv — move and rename

mv is the same operation as rename when source and destination are on the same filesystem — it just relinks the inode. Across filesystems it copies then deletes, which is slower and not atomic.

Same flags as cp where they apply: -i, -n, -v. There is no -r because mv always moves whatever you point at, recursive or not.

When to reach for rsync instead

For anything bigger than a few files, switch to rsync -av source/ dest/. It can resume, skip unchanged files, preserve permissions, and tell you exactly what it did. We dig into it in the network-remote track.

The trailing-slash quiz

  • cp -r dir1 dir2 — if dir2 exists, creates dir2/dir1. If not, creates dir2 as a copy.
  • cp -r dir1/ dir2/ — copies the contents of dir1 into dir2.
  • cp -r dir1/. dir2/ — same as above, more explicit.

Don't memorize. Always run cp -nv first, see the output, then drop the -n.

Code

Test before you commit·bash
# -nv = no overwrite, verbose. Shows the plan.
cp -rnv src/ dst/
# When the plan looks right
cp -rv src/ dst/
Atomic config swap with mv·bash
# Write the new file alongside, then mv replaces atomically
cat > /etc/myapp.conf.new <<EOF
key = value
EOF
mv /etc/myapp.conf.new /etc/myapp.conf

External links

Exercise

Make ~/sandbox/src with two files, then run cp -rv ~/sandbox/src ~/sandbox/dst1. Note the result. Now cp -rv ~/sandbox/src/ ~/sandbox/dst2/ (trailing slashes). Compare the two destination layouts.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.