Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 95 ยท Working with Files

Copying, Moving and Deleting

Learn cp, mv, rm and rmdir on Linux: copy files and directories, rename and move, delete safely, and avoid the classic mistakes that destroy data.

Creating files is only half of the job. Sooner or later you have to duplicate a file, rename it, move it somewhere else or get rid of it. Linux does these things with four small commands: cp (copy), mv (move or rename), rm (remove files) and rmdir (remove empty directories). They are short, fast and powerful, and they share one dangerous property: they do exactly what you typed, without asking, and there is no recycle bin.

This lesson teaches each command with real output, then the rules that explain their behaviour (especially the surprising ones: what happens when the destination already exists, why a trailing slash sometimes matters, and why rm -rf has such a reputation). It builds on Creating and Viewing Files; the next lesson, Wildcards and Globbing, shows how to act on many files at once.

Copying with cp

The basic form is cp SOURCE DEST. If DEST is an existing directory, the copy goes inside it, keeping its name. With several sources, the last argument must be a directory.

TEXT
cp a.txt b.txt            copy a.txt to a new file b.txt
cp a.txt b.txt backup/    copy both files into the directory backup/
Bash cp: copying files and the common errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the errors, they are precise. Copying a file onto itself is refused ('a.txt' and 'a.txt' are the same file), a missing source reports No such file or directory, and copying a directory without -r prints omitting directory. The last block shows the first rule to remember: cp overwrites an existing destination without a word. b.txt now contains new and the old content is gone for good.

You can protect yourself with options:

Option Meaning
-i, --interactive Ask before overwriting
-n, --no-clobber Never overwrite; skip silently
-u, --update Copy only when the source is newer than the destination (GNU)
-v, --verbose Print what is being copied
-b, --backup Keep the old destination as name~ (GNU)
Bash cp: no-clobber and verbose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

-i asks a question on the terminal, which is perfect when you type commands yourself and useless in scripts (there is nobody to answer). In scripts prefer -n or an explicit [[ -e "$dest" ]] test.

Copying directories

A directory is not a file with content, it is a container, so cp needs -r (--recursive) to walk into it. And here the destination rule bites: it depends on whether the destination already exists.

Bash cp -r and where the copy lands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

cp -r src dst1 created dst1/src/... because dst1 already existed. If dst1 had not existed, the very same command would have created dst1 as a copy of src. That "depends on whether it exists" behaviour is a classic trap in scripts that run twice: the first run creates dst/, the second run quietly creates dst/src/. Two cures:

  • Copy the contents with a trailing /., as in cp -r src/. dst/ (works on GNU and BSD, and dst must exist).
  • Use GNU -T (--no-target-directory), which always means "make the destination this exact name". macOS cp does not have -T.

On macOS and the BSDs, cp -r src/ dst copies the contents of src while on GNU/Linux the trailing slash on a source does not change the result. Do not rely on the slash; use src/. when you mean "the contents".

Keeping metadata: -p and -a

A plain copy creates a new file: new owner (you), new timestamps (now), and permissions filtered by your umask. When the metadata matters (backups, deployments), say so:

  • -p keeps mode, ownership (when allowed) and timestamps.
  • -a (--archive) is -dR --preserve=all: recursive, keeps symlinks as symlinks, and preserves everything it can. It is the right choice for "an exact copy of this tree".
Bash cp -p and -a keep metadata

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first line shows that plain.txt got fresh timestamps (the sed only replaces the volatile date by the word "today" so that the output is stable); preserved.txt kept 2026-01-01 12:00 and mode -rw-r-----. The last two lines show a subtle point: cp -a copies a symlink as a symlink, while a plain cp follows the link and copies the file it points to. Links explains symlinks in depth.

Moving and renaming with mv

Linux has no separate "rename" command. Renaming is moving to a different name, so one command, mv SOURCE DEST, does both:

TEXT
mv old.txt new.txt        rename
mv file.txt dir/          move into a directory (keeps the name)
mv a b c dir/             move several things into dir/
mv dir1 dir2              rename dir1 (if dir2 does not exist) or move it inside dir2 (if it does)
Bash mv: rename, move, and silent overwrite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Like cp, mv replaces an existing destination without asking (x now says new), unless you use -n (--no-clobber) or -i. With -b, GNU mv keeps the replaced file as x~.

What mv really does

Inside one filesystem, mv is almost free: it does not copy any data, it only changes a directory entry, the name that points to the file. That is why moving a 50 GB file within the same disk takes a millisecond, and why the file keeps its inode, permissions and timestamps. Between two filesystems (say /home to a USB drive), there is no way to relink, so mv copies the data and then deletes the original. This is slower, and if it is interrupted you may end up with two partial states. For huge cross-device moves, many professionals copy first, verify, and only then delete.

Because renaming only edits a directory entry, mv is also atomic on one filesystem: another program sees either the old name or the new one, never half a file. That is why safe scripts write to file.tmp and finish with mv file.tmp file.

To rename many files at once you combine mv with a loop or with the wildcards of the next lesson; see also the bulk-rename recipes in Text Processing Recipes.

Deleting with rm and rmdir

rm removes names. When the last name of a file disappears (and nobody has the file open) the data blocks are released. There is no trash can, no undelete, and on modern disks and SSDs recovery is usually impossible.

TEXT
rm file.txt          delete a file
rm -r dir            delete a directory and everything below it
rm -f file           never prompt, ignore files that do not exist
rm -i file           ask before every removal
rm -v file           print what was removed
rmdir dir            delete a directory, but only if it is empty
Bash rm, rmdir and their error messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The safe commands fail loudly: rm refuses a directory (Is a directory) and rmdir refuses a non-empty one (Directory not empty). Only when you add -r does rm descend and delete. rmdir is a useful safety net: use it to clean up directories you believe are empty, and it will refuse if you were wrong. rmdir -p a/b/c removes c, then b, then a, as long as each is empty.

The -f flag deserves respect. It suppresses "no such file" errors and confirmation prompts, which is useful in scripts (rm -f "$tmpfile" is fine if the file may not exist) but removes the last safety net when combined with -r.

Why rm -rf has a reputation

rm -rf PATH deletes everything below PATH immediately, silently, recursively. Most disasters are not typed deliberately; they come from an empty or wrong variable or a wrong working directory:

Terminal
# DO NOT RUN: shown only to explain the danger.
rm -rf "$BUILD_DIR"/*       # if BUILD_DIR is empty, this becomes rm -rf /*
rm -rf $dir/ tmp            # unquoted and with a stray space: also deletes ./tmp
rm -rf .*                   # matches ".." in old shells: climbs to the parent!

Habits that keep you safe:

  1. Look before you delete. Run ls or echo rm ... with the same pattern first; the shell expands the wildcard and you see the exact list.
  2. Quote variables and make them required. In scripts use rm -rf -- "${BUILD_DIR:?BUILD_DIR is not set}"/ so an empty variable aborts the script instead of widening the target (see Parameter Expansion).
  3. Use -- to end the options when a name could start with a dash.
  4. Use -v so the log shows what happened.
  5. Prefer a dry run with find: find build -name '*.o' first, then add -delete.
  6. Do not work as root unless you must. A normal user cannot delete system files.

GNU rm also refuses to remove / itself (--preserve-root is the default), but it cannot protect /home/you.

Names that look like options

A file can legally be called -rf. Then rm * expands to rm -rf other files, and the name is treated as an option! The cure is the -- marker ("everything after this is a name") or a path prefix such as ./*.

Bash Files named like options, and the -- marker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

(touch -- 'a b.txt' -rf created both files because of --. The listing shows -rf first because the sort order of LC_ALL=C puts punctuation before letters.)

Building a safer delete: a tiny trash

Since the system has no recycle bin, you can imitate one with mv. The idea is to move instead of delete, and let --backup=numbered keep earlier versions with the same name.

Bash A tiny trash function with mv --backup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Real desktop environments follow the freedesktop.org trash specification (~/.local/share/Trash) and tools such as trash-put from the trash-cli package use it, but this needs installing and does not exist in our sandbox. For servers the habits above matter more than a trash can: backups, version control (Git keeps every committed version) and care.

rm on a symlink deletes the link, not the target, but rm -r link/ with a trailing slash on a link to a directory is treated differently on some systems. See Hard Links, Symbolic Links and Inodes before deleting links to directories.

Splitting, wiping and legacy archives: csplit, shred and cpio

Three less common tools are worth knowing because each solves a problem that cp and rm cannot.

csplit: split a file at patterns

split cuts a file into equal pieces by size or line count. csplit cuts it at content: at given line numbers or wherever a regular expression matches. The pieces are named xx00, xx01, ... unless you pass -f prefix.

Terminal
csplit -z -s -f part- file.txt 4 8        # lines 1-3, 4-7, 8-end
csplit -z -s -f sec- doc.md '/^## /' '{*}' # one piece per "## " heading
csplit -z -f log- app.log '%ERROR%' '/ERROR/' '{3}'   # skip to the first ERROR, then 3 more cuts

A line number starts a new piece at that line. /re/ cuts just before the matching line; %re% skips ahead without writing a piece; repeats the previous pattern N more times and {*} as often as it matches. -s hides the byte counts, -z drops empty pieces and -b '%03d' changes the suffix format.

Bash Split a document at its headings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

shred: overwrite before deleting

rm only removes the directory entry; the data blocks stay on disk until reused, and tools can recover them. shred overwrites the file's blocks first (-n 3 passes, -z adds a final pass of zeros, -u removes the file afterwards, -v shows progress).

Terminal
shred -v -n 3 -z -u old-keys.txt

Be honest about what it can do: it works on a file whose blocks are rewritten in place. On journaling file systems in data=journal mode, copy-on-write systems (btrfs, ZFS), SSDs with wear levelling, RAID, snapshots and network storage, old copies may survive elsewhere. For whole devices, use full-disk encryption from the start and destroy the key; shred /dev/sdX is for disks you are about to retire.

Bash Wipe and remove a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

cpio: the other archiver

cpio ("copy in, copy out") is still used in two places: RPM packages (the payload of an .rpm is a cpio archive) and the Linux initramfs (the early-boot image is a compressed cpio archive). Unlike tar, it does not walk directories itself: you feed it a list of names on standard input, which makes it a natural partner for find.

Terminal
$ find src -name '*.c' | cpio -o > sources.cpio      # -o: copy out (create)
$ cpio -it < sources.cpio                            # -i -t: list contents
$ mkdir restore && cd restore
$ cpio -id < ../sources.cpio                         # -i extract, -d create directories
$ find . -depth | cpio -pdm /backup/tree             # -p: pass-through copy, -m keep mtimes
$ zcat /boot/initrd.img-* | cpio -it | head          # peek inside an initramfs

The three modes are -o (create from a list of names), -i (extract) and -p (copy a tree to another place without making an archive). Our sandbox has no cpio, so use tar in daily work and remember cpio when you meet an RPM or an initramfs; see Archives and Compression for tar.

When to use what

  • Same filesystem, rename or reorganise: mv. It is instant and atomic.
  • Duplicate a tree faithfully: cp -a. Duplicate only content: cp -r src/. dst/.
  • Large or repeated transfers where you want resumption and progress: rsync (not in our sandbox; the idea is rsync -a src/ dst/, and for rsync a trailing slash on the source does mean "contents of").
  • Delete files: rm; delete an empty directory: rmdir; delete a tree: rm -r, after looking.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run cp -r src dst and dst already exists. Where does the copy of src end up?

    If the destination directory exists, cp -r places the source inside it, giving dst/src. If dst did not exist, the copy would be named dst. Use src/. or GNU -T for predictable behaviour.
  2. 2. Why is moving a huge file with mv inside one filesystem nearly instant?

    A move inside one filesystem rewrites the name that points at the inode. No data blocks move, so the file keeps its inode and timestamps.
  3. 3. Which command does NOT silently overwrite an existing file named b.txt?

    cp and mv both replace the destination without asking unless you add -n/--no-clobber (or -i to be asked). The last option is wrong because --no-clobber is the built-in way.
  4. 4. A script runs rm -rf "$DIR"/* and DIR is accidentally empty. What does the shell run?

    An empty variable expands to nothing, leaving /* which is every top-level directory. Use ${DIR:?} so the script aborts when the variable is empty.
  5. 5. A file is named -rf. How do you delete it safely?

    Quotes do not change how rm sees the argument; it still starts with a dash. -- ends option parsing and ./-rf makes the name start with a dot.

Summary

  • cp SRC DEST copies; cp -r copies directories, -p keeps timestamps and mode, -a makes an archive-quality copy (and keeps symlinks as symlinks).
  • cp -r src dst behaves differently depending on whether dst exists; use src/. or GNU -T for predictable results.
  • mv both moves and renames; on one filesystem it only edits a directory entry, so it is instant and atomic.
  • cp and mv overwrite silently; use -n, -i or -b to protect existing files.
  • rm is permanent. rm -r deletes trees, rm -f removes the safety net, rmdir only removes empty directories.
  • Look before you delete (ls, echo), quote variables, use ${var:?} and --, and prefer -v.

Next: Wildcards and Globbing