Quiz 2

File Operations — Essential Commands

1019 words
5 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# File Operations — Essential Commands ## 🎯 Learning Objectives - Create, copy, move, rename, and delete files and directories - Use wildcards for batch operations - Understand hard links vs symbolic links - Use `find` to locate files ## 1. Creating Files and Directories ## 2.

File Operations — Essential Commands

🎯 Learning Objectives

  • Create, copy, move, rename, and delete files and directories
  • Use wildcards for batch operations
  • Understand hard links vs symbolic links
  • Use find to locate files

1. Creating Files and Directories

bash
# Create empty file
touch file.txt
touch file1.txt file2.txt file3.txt  # Multiple files
# Create directory
mkdir mydir
mkdir -p path/to/nested/dir  # Create parent directories as needed
mkdir -p {dir1,dir2,dir3}    # Create multiple directories
# Create file with content
echo "Hello, World!" > hello.txt
echo "Line 1" > file.txt      # Overwrite
echo "Line 2" >> file.txt     # Append

2. Listing Files — ls

bash
ls                  # Basic listing
ls -l               # Long format (permissions, owner, size, date)
ls -a               # Show hidden files (starting with .)
ls -la              # Combined
ls -lh              # Human-readable sizes (1K, 2M, 3G)
ls -lt              # Sort by modification time (newest first)
ls -lS              # Sort by file size (largest first)
ls -R               # Recursive (show subdirectories)
ls *.txt            # Wildcard: all .txt files
ls file[0-9].txt    # file1.txt, file2.txt, ..., file9.txt

3. Copying — cp

bash
cp source.txt dest.txt                    # Copy file
cp -i source.txt dest.txt                 # Interactive (prompt before overwrite)
cp -v source.txt dest.txt                 # Verbose (show what's being copied)
cp file.txt /path/to/dir/                 # Copy to directory (same name)
cp -r sourcedir/ destdir/                  # Copy directory recursively
cp -u source.txt dest.txt                 # Copy only if source is newer
# Copy multiple files to directory
cp file1.txt file2.txt file3.txt /target/
cp *.txt /target/                         # Copy all .txt files

4. Moving and Renaming — mv

bash
mv oldname.txt newname.txt    # Rename file
mv file.txt /path/to/dir/     # Move file to directory
mv -i source dest             # Interactive (prompt before overwrite)
mv -v source dest             # Verbose
mv source1 source2 dir/       # Move multiple files to directory
mv dir1/ dir2/                # Rename or move directory

5. Deleting — rm

bash
rm file.txt                   # Delete file
rm -i file.txt                # Interactive (ask before delete)
rm -v file.txt                # Verbose
rm -f file.txt                # Force (no prompt, ignore nonexistent)
rm -r dir/                    # Delete directory recursively
rm -rf dir/                   # Delete directory without prompting ⚠️
# ⚠️ DANGEROUS — be extremely careful:
rm -rf /                      # Delete EVERYTHING (don't run!)
rm -rf ./*                    # Delete all files in current directory

6. Wildcards (Globbing)

PatternMatchesExample
*Any characters*.txt = all .txt files
?Single characterfile?.txt = file1.txt, fileA.txt
[abc]One of a, b, cfile[12].txt = file1.txt, file2.txt
[a-z]Rangefile[a-z].txt = filea.txt, ..., filez.txt
[!abc]NOT a, b, cfile[!0-9].txt = fileA.txt, not file1.txt
{a,b,c}Brace expansion{1,2,3}.txt = 1.txt, 2.txt, 3.txt
bash
# Examples
ls *.txt                    # All text files
ls file[0-9].txt            # file0.txt to file9.txt
cp *.jpg ~/Pictures/        # Copy all JPEGs
rm -rf temp_{1,2,3}/        # Delete temp_1, temp_2, temp_3

7. Finding Files — find

bash
# Basic usage
find . -name "*.txt"             # Find all .txt files starting from current dir
find /home -name "*.pdf"         # Find PDFs in /home
find . -type f -name "*.log"     # Find only files (not directories)
find . -type d -name "backup"    # Find directories named "backup"
# By size
find . -size +1M                 # Files larger than 1 MB
find . -size -10k                # Files smaller than 10 KB
# By time
find . -mtime -7                 # Modified in last 7 days
find . -mmin -60                 # Modified in last 60 minutes
# Execute action on found files
find . -name "*.tmp" -delete     # Delete all .tmp files
find . -name "*.py" -exec wc -l {} \;   # Count lines in Python files
# Combining with xargs
find . -name "*.log" -mtime +30 | xargs rm  # Remove old logs
bash
# Symbolic link (like a shortcut)
ln -s target.txt link.txt        # Create symbolic link
ls -l                             # Shows link with -> target
# Hard link (another name for same file)
ln target.txt hardlink.txt        # Both point to same inode/data
ls -l                             # Shows link count > 1
Symbolic link: Points to filename. Breaks if target is deleted. Can cross filesystems. Hard link: Points to data (inode). Continues to work if original is deleted. Cannot cross filesystems.

9. Practice Questions

Q1: What's the difference between cp and mv?
Answer: cp creates a copy (source remains, new copy created). mv moves/renames (source no longer exists at original location). mv is also used for renaming. Q2: What does mkdir -p a/b/c do?
Answer: Creates nested directories: a, then a/b, then a/b/c. Without -p, it would fail if a or a/b don't exist. Q3: What is the difference between *, ?, and [abc] wildcards?
Answer: * matches any number of characters (including zero). ? matches exactly one character. [abc] matches exactly one character from the set {a, b, c}. Q4: How do you delete a directory and all its contents?
Answer: rm -rf dirname/. -r (recursive) deletes the directory and all contents. -f (force) skips prompts. Be very careful with this command. Q5: What does touch do when the file already exists?
Answer: It updates the file's modification and access timestamps to the current time without changing the file contents. It does NOT delete or modify the file. Q6: What's the difference between a hard link and a symbolic link?
Answer: Symbolic link: points to filename (breaks if target deleted, can cross filesystems). Hard link: points to inode/data (survives original deletion, can't cross filesystems, can't link directories). ls -l shows link type. Q7: How do you find all .log files larger than 100MB?
Answer: find / -name "*.log" -size +100M Q8: What does rm -i do?
Answer: Interactive mode — prompts for confirmation before deleting each file. Useful with wildcards to avoid accidental deletion.

📐 Key Concepts

CommandPurposeCommon Options
lsList files-l, -a, -h, -R
cpCopy files-r, -i, -v, -u
mvMove/rename-i, -v
rmDelete files-r, -f, -i
mkdirCreate directory-p
touchCreate/update file
findSearch files-name, -type, -size
lnCreate links-s (symbolic)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.