Lab 06: Deleting Files and Directories

Objective

Use rm, rmdir, glob patterns, and understand why Linux has no Recycle Bin. Learn safe deletion practices that prevent catastrophic mistakes in production.

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


Step 1: Deleting a Single File

touch /tmp/test.txt /tmp/test2.txt /tmp/test3.txt
rm /tmp/test.txt
ls /tmp/test*

📸 Verified Output:

/tmp/test2.txt
/tmp/test3.txt

💡 Linux has no Recycle Bin. rm permanently deletes. There is no "undo". In a container or test environment this is fine — on a production server, one wrong rm -rf can be catastrophic.


Step 2: Deleting Directories

mkdir /tmp/empty_dir
rmdir /tmp/empty_dir    # works on empty directories only
echo "Exit code: $?"    # 0 = success

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:

💡 rm -r is powerful — it deletes everything inside a directory tree. Always double-check the path before running it.


Step 3: Glob Patterns for Batch Deletion

📸 Verified Output:

📸 Verified Output:

💡 Always test your glob before deleting. Run ls /path/*.txt first, confirm it shows what you expect, then replace ls with rm. This habit prevents disasters.


Step 4: Interactive Deletion (-i flag)

📸 Verified Output:

💡 Some sysadmins alias rm='rm -i' in their .bashrc on servers. In scripts, use -f (force, no prompts). In interactive use, -i adds a safety net.


Step 5: Verbose Deletion (-v flag)

📸 Verified Output:

💡 -v prints each file as it's deleted. Useful when running rm in scripts so you have an audit trail of exactly what was removed.


Step 6: The Danger of rm -rf

📸 Verified Output:

💡 The infamous rm -rf / would delete your entire system. Modern Linux distributions add a --no-preserve-root safeguard that you must explicitly add to override. Never run commands with -rf without triple-checking the path.


Step 7: Securely Deleting Sensitive Files

📸 Verified Output:

💡 On SSDs, shred and dd overwrites are unreliable due to wear-leveling. True secure deletion on SSDs requires full-disk encryption (dm-crypt) so deleted files are unrecoverable by default.


Step 8: Capstone — Safe Log Rotation Cleanup

📸 Verified Output:


Summary

Command
Purpose

rm file

Delete a file

rm -r dir

Delete directory recursively

rm -rf dir

Force recursive delete (no prompts)

rm -i file

Prompt before each deletion

rm -v file

Verbose: show each deletion

rmdir dir

Delete empty directory only

find -mtime +N -delete

Delete files older than N days

Last updated