Linux: File and Directory Operations
In the Linux terminal, creating, copying, moving, and deleting files is just a few keystrokes — faster and more precise than using a mouse.
📋 Prerequisites: You should first complete
- Lesson 4: Filesystem Navigation
1. What You Will Learn
- touch: create files and update timestamps
- mkdir: create directories (including -p for recursive)
- cp: copy files and directories
- mv: move and rename
- rm: safe deletion (including -rf risk warning)
2. Alex Learns to Create an Entire Project Structure in One Line
(1) The Pain: Creating Directories Layer by Layer with Right-Clicks
Alex wanted to create a project directory structure: myblog/src/css, myblog/src/js, myblog/docs. On Windows he had to right-click → New Folder, creating each layer manually — repetitive work every time.
(2) One Command Creates the Entire Structure
Senior engineer Bob typed one line in his terminal:
mkdir -p myblog/{src/{css,js,img},docs}
After pressing Enter, tree myblog showed:
myblog/
├── src/
│ ├── css/
│ ├── js/
│ └── img/
└── docs/
Alex was amazed. He finally understood why developers love the terminal.
(3) The Benefit: Operation Efficiency Skyrockets
After learning the five file operation commands, Alex's speed for creating and organizing files went from "minutes" to "seconds."
3. Knowledge Points
(1) touch — Create Files or Update Timestamps
touch filename
If the file doesn't exist, touch creates an empty file. If it exists, its access and modification times are updated to the current time.
(2) mkdir — Create Directories
mkdir dirname # Create a single directory
mkdir -p a/b/c # Recursive creation (auto-creates parent directories if they don't exist)
mkdir dir1 dir2 dir3 # Create multiple directories at once
mkdir -p src/{css,js} # Brace expansion for batch creation
> 💡 Tip: `mkdir -p` combined with brace expansion `{a,b,c}` is a powerful bash combination — `mkdir -p project/{src/{css,js},docs}` creates an entire project directory tree in one line, much faster than creating each layer individually.
(3) cp — Copy
cp source destination # Copy a file
cp -r source_dir dest_dir # Recursively copy a directory
cp -i source destination # Interactive mode (confirm before overwriting)
cp -u source destination # Copy only if the source is newer
cp -v source destination # Show copy progress
cp -p source destination # Preserve file attributes (permissions/timestamps)
(4) mv — Move and Rename
mv oldname newname # Rename
mv file.txt /path/to/dest/ # Move file to another directory
mv dir1 dir2 # Rename if dir2 doesn't exist; move into if it does
mv -i source dest # Confirm before overwriting
mv -u source dest # Move only if source is newer
(5) rm — Delete
rm file.txt # Delete a file
rm -r dirname # Recursively delete a directory
rm -f file.txt # Force delete (no confirmation prompt)
rm -i file.txt # Interactive mode (confirm before deleting)
rm -rf dirname # Recursive force delete (⚠️ dangerous combination)
rm -rf / will delete the entire system. Never run rm -rf / as root. Get in the habit of using -i for daily operations.
rm -rf do not go to a recycle bin and cannot be recovered through normal means. Before using rm -rf, always confirm your current directory (pwd) and the path you're deleting to avoid accidental deletion. Consider adding alias rm='rm -i' to your .bashrc as a safety net.
(6) Hard Links vs Symbolic Links
| Feature | Hard link | Symbolic link (symlink) |
|---|---|---|
| Command | ln target link_name |
ln -s target link_name |
| inode | Same as original file | Different |
| Cross-filesystem | No | Yes |
| Can link directories | No | Yes |
| After original deleted | Link still works | Link breaks (dangling link) |
| File size | Same as original | Only stores the path string |
# Hard link
ln original.txt hardlink.txt
# Symbolic link
ln -s /usr/bin/python3 python3
(7) ▶ Example: Create Files and Directories
# Create empty files
touch index.html
touch style.css script.js # Create multiple at once
# Create directories
mkdir projects
mkdir -p projects/web/src/css # Recursively create nested directories
# Brace expansion (bash feature)
mkdir -p {2024,2025,2026}/{01,02,03}
# Creates: 2024/01, 2024/02, 2024/03, 2025/01, ...
Output:
TEXT2024: 01 02 03 2025: 01 02 03 2026: 01 02 03
(8) ▶ Example: Copy Files
# Copy a single file
cp index.html index.backup.html
# Copy a directory (requires -r)
cp -r projects projects-backup
# Interactive mode to prevent accidental overwrite
cp -i important.txt /backup/
# Preserve file attributes
cp -p config.conf /backup/
Output:
TEXTcp: overwrite '/backup/important.txt'? n
(9) ▶ Example: Move and Rename
# Rename a file
mv old-report.md report-2026.md
# Move to another directory
mv report.md ~/Documents/reports/
# Batch rename (using a loop)
for f in *.html; do mv "$f" "${f%.html}.htm"; done
Output:
TEXT(No output, file has been renamed)
(10) ▶ Example: Safe Deletion
# Safety first: interactive mode
rm -i file.txt
# Delete an empty directory
rmdir empty-dir
# Delete a non-empty directory
rm -r old-project/
# Use with caution (deletes without prompting)
rm -f temp.log
(11) ▶ Example: Batch Operations with Wildcards
# Copy all .jpg files
cp *.jpg ~/Pictures/
# Delete all .tmp temporary files
rm *.tmp
# Move files starting with 2024
mv 2024* ~/archive/
# List files ending with a digit
ls *[0-9]
Output:
TEXTreport2024.md log2025.txt backup1.tar.gz
(12) ▶ Comprehensive Example: Create a Complete Project Directory Structure
# Alex creates his blog project (one line does it all)
mkdir -p myblog/{src/{css,js,img},docs,scripts,test}
# Create an HTML index file under src
touch myblog/src/index.html
# Copy as a backup
cp -r myblog myblog-backup
# Rename the backup directory
mv myblog-backup myblog-2026-07
# View the final structure
find myblog -type f -o -type d | sort
❓ FAQ
Q: Will
rm -rf /really delete the entire system? A: \1
Q: What's the difference between cp and mv when operating on directories? A:
cprequires the-rflag to copy directories (recursive).mvdoesn't — moving a directory uses the same command as moving a file. If the target directory doesn't exist,mvrenames; if it exists, the source is moved inside it.
Q: How do I handle filenames with spaces? A: \1
Q: How do I batch rename files? A: Use a
forloop:for f in *.jpg; do mv "$f" "prefix_$f"; done, or the dedicatedrenametool:rename 's/\.jpg$/\.png/' *.jpg.
Q: What happens if I delete the original file of a symbolic link? A: The symlink becomes a "broken link" —
ls -lwill show a flashing red name, and accessing it will give aNo such file or directoryerror. Hard links are unaffected (because they point directly to the original file's inode).
📖 Summary
touchcreates empty files;mkdir -pcreates nested directoriescp -rcopies directories;mvmoves or renames;rm -rdeletes directories- Brace expansion
{a,b,c}enables batch creation lncreates hard links;ln -screates symbolic linksrm -rfis a dangerous combination — always confirm your current directory and identity before executing
📝 Exercises
- Basic (Difficulty ⭐): Use
mkdir -pto create the directory treelinux/assignments/{hw1,hw2,hw3}/{src,docs}, and use brace expansion to createmain.pyin each hw's src subdirectory - Intermediate (Difficulty ⭐⭐): Copy hw3 as hw4 and verify, then delete hw1/src/main.py, and use
rm -rto delete the entire hw2 directory - Advanced (Difficulty ⭐⭐⭐): Create a symbolic link pointing to
/etc/hostnameand verify it, then write a one-liner usingfindto locate all themain.pyfiles you created and batch rename them tomain.sh