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

1. What You Will Learn


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:

BASH
mkdir -p myblog/{src/{css,js,img},docs}

After pressing Enter, tree myblog showed:

TEXT

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

BASH
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

BASH
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

BASH
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

BASH
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

BASH
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)
⚠️ Safety Warning: rm -rf / will delete the entire system. Never run rm -rf / as root. Get in the habit of using -i for daily operations.

⚠️ Note: Files deleted with 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.

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
TEXT
# Hard link
ln original.txt hardlink.txt

# Symbolic link
ln -s /usr/bin/python3 python3

(7) ▶ Example: Create Files and Directories

BASH
# 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:

TEXT
2024:
01  02  03
2025:
01  02  03
2026:
01  02  03

(8) ▶ Example: Copy Files

BASH
# 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:

TEXT
cp: overwrite '/backup/important.txt'? n

(9) ▶ Example: Move and Rename

BASH
# 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

TEXT
# 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

BASH
# 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:

TEXT
report2024.md  log2025.txt  backup1.tar.gz

(12) ▶ Comprehensive Example: Create a Complete Project Directory Structure

BASH
# 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: cp requires the -r flag to copy directories (recursive). mv doesn't — moving a directory uses the same command as moving a file. If the target directory doesn't exist, mv renames; 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 for loop: for f in *.jpg; do mv "$f" "prefix_$f"; done, or the dedicated rename tool: 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 -l will show a flashing red name, and accessing it will give a No such file or directory error. Hard links are unaffected (because they point directly to the original file's inode).


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Use mkdir -p to create the directory tree linux/assignments/{hw1,hw2,hw3}/{src,docs}, and use brace expansion to create main.py in each hw's src subdirectory
  2. Intermediate (Difficulty ⭐⭐): Copy hw3 as hw4 and verify, then delete hw1/src/main.py, and use rm -r to delete the entire hw2 directory
  3. Advanced (Difficulty ⭐⭐⭐): Create a symbolic link pointing to /etc/hostname and verify it, then write a one-liner using find to locate all the main.py files you created and batch rename them to main.sh
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏