Course outline · 0% complete

0/29 lessons0%

Course overview →

Copying and moving: cp and mv

lesson 3-2 · ~10 min · 8/29

cp copies, mv moves AND renames

These two are the workhorses of file organization: back up a config file before you edit it, pull a download into the right project, fix a bad filename. You'll type them daily.

  • cp source destination: makes a copy. The original stays. For directories you need cp -r (r for recursive, meaning "and everything inside").
  • mv source destination: moves the file. The original is gone from its old place.

Here's the part beginners miss: renaming is just moving. mv old-name.txt new-name.txt "moves" the file to a new name in the same directory. There is no separate rename command in daily use.

Both commands overwrite the destination silently if it already exists, so read your command once before pressing Enter.

cp a.txt b.txta.txtb.txttwo files exist aftermv a.txt b.txta.txtb.txtonly one file exists after
cp leaves the original in place. mv takes it away, which is also how files get renamed.

Code exercise · bash

Run it. We write a file, cp it to a backup, then mv (rename) the original. ls shows both names, and cat proves the backup kept the text.

Code exercise · bash

Directories need `-r`. Plain cp refuses a directory, because copying one means copying everything inside it — `-r` (recursive) says to do exactly that. Run it: the backup contains the same tree.

Quiz

You run `mv notes.txt notes-old.txt` inside one directory. What happens?

Quiz

You want to rename notes.txt to ideas.txt. Which command does it?

Code exercise · bash

Your turn. Make a directory `safe`, write "top secret" into `plan.txt`, copy it INTO safe/ as `plan-copy.txt`, then rename the original to `renamed-plan.txt`. Finish with `ls` then `ls safe`. Expected output: ``` renamed-plan.txt safe plan-copy.txt ```