
File Operations: cp, mv, rm, mkdir, and rmdir
Master the fundamental actions of file management. Learn to copy, move, and delete files with safety and precision. Understand recursive operations, forced deletions, and how to stay safe from the 'rm -rf /' disaster.
File Operations: Moving, Copying, and Deleting
In the previous lesson, we learned how to look around the Linux tree. Now, we are going to learn how to change it. Managing files is the "bread and butter" of system administration and development. Whether you are deploying a new app, backing up a database, or cleaning up logs, you will use these five commands every single day.
However, with great power comes great responsibility. Unlike Windows, the Linux command line has no "Recycle Bin." When you delete a file, it is gone forever. This lesson will teach you how to perform these operations both efficiently and safely.
1. mkdir: Growing the Tree
To create a new directory (folder), use mkdir.
mkdir projects
The "-p" (Parents) Power User Flag
If you want to create a nested structure like app/src/utils, a normal mkdir will fail because the app folder doesn't exist yet. Use -p to create the entire path at once.
mkdir -p app/src/utils
2. cp: Duplicating Data
cp (Copy) takes two arguments: the Source and the Destination.
cp recipe.txt recipe_backup.txt
Special Flags for cp:
cp -r: Recursive. Essential for copying entire folders.cp -i: Interactive. Asks for permission before overwriting an existing file. (Highly recommended!)cp -p: Preserve. Keeps the original timestamps and permissions.
3. mv: Moving and Renaming
In Linux, Moving and Renaming are the same thing. To rename a file, you simply "move" it from its old name to its new name.
# Renaming a file
mv old_name.txt new_name.txt
# Moving a file to a different folder
mv file.txt ./backups/
4. rm: The Dangerous Command
rm (Remove) is the most dangerous tool in your kit. By default, it works silently and permanently.
Safety First:
rm -i: Asks "Are you sure?" for every file.rm -r: Recursive. Used to delete folders and their contents.rm -f: Force. Deletes files without asking any questions, even if they are write-protected.
The Nuclear Option: rm -rf
You will often see tutorials tell you to use rm -rf /path/to/folder. Be extremely careful. If you accidentally type a space in the middle—like rm -rf / path/to/folder—the command will attempt to delete everything starting from the system root (/).
Modern Linux has "safe-guards" against this, but never rely on them.
5. Practical: The Safe-Copy Workflow
When you are about to edit a critical configuration file (like /etc/nginx/nginx.conf), professional admins always follow this "Safety Copy" routine:
# 1. Create a timestamped backup before touching the file
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak.$(date +%F)
# 2. Now you can safely edit the original
sudo nano /etc/nginx/nginx.conf
6. Example: A Garbage Collector Script (Python)
If you have a server with a /tmp folder that fills up with old logs, you need a script to clean it up safely. This Python script mimics rm but adds a "Date Check" so it only deletes files older than 7 days.
import os
import time
def cleanup_old_files(directory, days_threshold=7):
"""
Deletes files in a directory that haven't been modified
in the specified number of days.
"""
now = time.time()
# Convert days to seconds
threshold_seconds = days_threshold * 86400
print(f"Starting cleanup in {directory}...")
print(f"Targeting files older than {days_threshold} days.")
files_deleted = 0
bytes_freed = 0
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# We only want to delete files, not nested directories (safety)
if os.path.isfile(file_path):
file_mod_time = os.path.getmtime(file_path)
if (now - file_mod_time) > threshold_seconds:
size = os.path.getsize(file_path)
try:
os.remove(file_path)
files_deleted += 1
bytes_freed += size
print(f" [X] Deleted: {filename}")
except Exception as e:
print(f" [!] Failed to delete {filename}: {e}")
print("-" * 35)
print(f"Cleanup Complete. Deleted {files_deleted} files.")
print(f"Freed up {bytes_freed / (1024*1024):.2f} MB.")
if __name__ == "__main__":
# WARNING: Be careful which directory you put here!
# A safe test is a folder you create yourself.
test_dir = "./tmp_test_folder"
if not os.path.exists(test_dir):
os.mkdir(test_dir)
cleanup_old_files(test_dir)
7. Professional Tip: Use 'mv' for Atomic Ops
If you are updating a website, don't copy files one by one into the production folder. This can cause the site to break mid-copy.
- Copy your new files into a temporary folder:
new_v2/. - Delete the old symlink:
rm current_site. - Rename the new folder to the official name:
mv new_v2 current_site. This switch happens almost instantly (atomically).
8. Summary
File operations are the fundamental tools of your trade.
mkdir -pbuilds your structure quickly.cp -iprotects you from overwriting your work.mvis used for both moving and renaming.rmhas no "Undo" button—use it with extreme caution.
In the next lesson, we will learn how to View Files without moving or deleting them, using tools like cat, less, head, and tail.
Quiz Questions
- How do you rename a file from
index.htmltohome.html? - What is the difference between
mkdir projectandmkdir -p project/src/v1? - If you want to delete a directory named
old_backupsthat contains 500 files, which command and flags should you use?
Continue to Lesson 4: Viewing Files—cat, less, more, head, and tail.