Lab 05: Copying and Moving Files

Objective

Master cp, mv, directory copies, backup strategies, and diff for comparing files. These operations are fundamental to configuration management, backup scripts, and incident response.

Time: 25 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: Setup — Create Files to Work With

mkdir -p /tmp/lab5
cp /etc/passwd /tmp/lab5/
ls -la /tmp/lab5/

📸 Verified Output:

total 12
drwxr-xr-x 2 root root 4096 Mar  5 00:55 .
drwxrwxrwt 1 root root 4096 Mar  5 00:55 ..
-rw-r--r-- 1 root root  922 Mar  5 00:55 passwd

Step 2: Copying Files

# Copy to new name (same directory)
cp /tmp/lab5/passwd /tmp/lab5/passwd.bak
ls -la /tmp/lab5/

📸 Verified Output:

📸 Verified Output:

💡 cp source destination — if destination is a directory, the file goes inside it. If destination is a new name, the file is copied with that name.


Step 3: Copying Directories (Recursive)

📸 Verified Output:

💡 -r means recursive — copy the directory and everything inside it. Without -r, cp refuses to copy directories. Use cp -rp to also preserve timestamps and permissions.


Step 4: Moving and Renaming with mv

📸 Verified Output:

📸 Verified Output:

💡 Unlike cp, mv does not leave the original behind. On the same filesystem, mv is instant (it just changes the directory entry). Cross-filesystem mv actually copies then deletes.


Step 5: Comparing Files with diff

📸 Verified Output:

📸 Verified Output:

💡 diff output: 19a20 means "after line 19 of file1, add line 20 of file2". > marks lines in file2. < marks lines in file1. This is exactly the format used in Git patches.


Step 6: Preserving Metadata

📸 Verified Output:

💡 Use -p (preserve) when making config backups — you want the backup to reflect when the original was last legitimately changed, not when you made the backup.


Step 7: Safe Moves with Confirmation

📸 Verified Output:


Step 8: Capstone — Incident Response Backup Script

📸 Verified Output:


Summary

Command
Purpose

cp src dst

Copy file

cp -r src dst

Copy directory recursively

cp -p src dst

Copy preserving metadata

mv src dst

Move or rename

diff file1 file2

Show differences between files

Last updated