惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
Simon Willison's Weblog
Simon Willison's Weblog
B
Blog
V
Visual Studio Blog
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
S
SegmentFault 最新的问题
博客园 - 司徒正美
博客园 - 【当耐特】
T
Tenable Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium
S
Secure Thoughts
Hugging Face - Blog
Hugging Face - Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
IT之家
IT之家
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
大猫的无限游戏
大猫的无限游戏
PCI Perspectives
PCI Perspectives
H
Hackread – Cybersecurity News, Data Breaches, AI and More
阮一峰的网络日志
阮一峰的网络日志
P
Privacy International News Feed
N
News and Events Feed by Topic
H
Hacker News: Front Page
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
F
Full Disclosure
Google Online Security Blog
Google Online Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Heimdal Security Blog
Project Zero
Project Zero
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
AI
AI
月光博客
月光博客
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
L
Lohrmann on Cybersecurity
TaoSecurity Blog
TaoSecurity Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
CXSECURITY Database RSS Feed - CXSecurity.com
Spread Privacy
Spread Privacy
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
SecWiki News
SecWiki News
C
Cisco Blogs
The Last Watchdog
The Last Watchdog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
You’re Already Using Git Worktrees. You Should Understand Them.
Vivek Maskar · 2026-05-18 · via DEV Community

If you’ve ever run git clone and then started editing files in the resulting folder, you’ve been using a Git worktree all along. Git just doesn’t call it that in day-to-day conversation.

git worktree is the feature that lets you add more checkouts (more folders with files on disk) that all share the same underlying repository history. Done well, it replaces the “stash/switch/stash-back” dance with something simpler: keep your in-progress work open in one directory, and do the urgent/clean/experimental thing in another.

This is a mental-model article: what a worktree is, why Git enforces “one branch per worktree,” and the few lifecycle commands that keep worktrees from turning into confusing “already checked out” / stale-metadata problems.

The Mental Model: Shared History, Separate Working State

Git’s own git worktree docs describe the feature as managing “multiple working trees attached to the same repository.” The twist is that you always start with one: the directory you land in after a normal (non-bare) clone is the main worktree.

Linked worktrees are additional working directories attached to the same repo. They share the object database (commits/trees/blobs), but each worktree has its own working state: checked-out files, its own HEAD, and its own index (staging area).

That’s the whole trick:

  • Shared: history and objects (you don’t redownload Git data like a second clone).
  • Per worktree: files-on-disk + HEAD + index (you don’t stomp on your other checkout).

One nuance that matters: a worktree isn’t its own independent “repo.” Most refs and remote configuration are shared. When you git fetch, you’re updating the shared repository data that all worktrees see. That’s what makes worktrees lighter than multiple clones—but it’s also why Git has to be careful about how a branch name maps to a checkout.

If you want a deeper explanation of why “objects live once” makes this efficient, the Git book’s “Git Objects” chapter is a good reference: Git Internals: Git Objects.

Diagram

What Actually Changes on Disk when You Add a Worktree

Git keeps the shared repository database in one place, then tracks per-worktree state separately. That’s why it can add a second checkout without cloning.

If you’ve ever noticed that .git sometimes looks like a file (not a folder), that’s often Git pointing your working tree at the real “gitdir.” Worktrees lean on this idea heavily: each worktree has its own admin area, but the objects are shared.

The Rule that Surprises People: One Branch per Worktree

If you try to attach the same branch to two worktrees, Git will usually refuse with “branch is already checked out.” That refusal is protection.

The core reason is that a branch name is just a movable pointer. If two working directories could both “be” feature, the branch pointer could move in one directory while the other directory still has older files on disk. Now you have a branch name that no longer uniquely identifies a single working state.

Said differently: Git is fine with multiple worktrees having different HEADs (each checkout is independent), but a branch ref like refs/heads/feature is shared at the repository level. Letting two worktrees both “own” the same branch would create a footgun where “what commit is feature?” depends on which folder last advanced it.

Git worktree visualized

When you want “two directories, same starting point,” Git’s safer options are:

  • Create a new branch name for the second worktree:
git worktree add ../wt-fix -b fix-branch

Enter fullscreen mode Exit fullscreen mode

  • Use a detached HEAD when you don’t intend to keep the work long-term:
git worktree add -d ../wt-scratch

Enter fullscreen mode Exit fullscreen mode

Detached HEAD is the “I want another directory at this commit, but I’m not claiming a branch name” mode. That’s why it’s safe: you can still make commits, but you’re not advancing a shared branch ref unless you later create one.

--force exists for edge cases, but it’s opting out of a guardrail. If you don’t already know why you need it, you probably don’t.

Where Worktrees Shine (in Practice)

Worktrees are a productivity primitive whenever parallelism beats context switching. Three common patterns:

1) Hotfix without Touching Your In-Progress Directory

When a production issue lands mid-feature, create a new worktree on a hotfix branch:

git worktree add ../wt-hotfix -b hotfix

Enter fullscreen mode Exit fullscreen mode

You get a clean checkout in a new folder, and your original directory stays exactly as it was. When you’re done, remove it cleanly:

git worktree remove ../wt-hotfix

Enter fullscreen mode Exit fullscreen mode

Tower’s Git worktree FAQ describes this as one of the “default” worktree use cases, and it’s the one most people feel immediately.

2) PR Reviews and Repros in a Clean Sandbox

You can attach a worktree directly to a remote-tracking branch and keep it around for as long as the review takes:

git worktree add ../wt-review origin/some-pr-branch

Enter fullscreen mode Exit fullscreen mode

3) Scratch Experiments You Don’t Want to Keep

Detached worktrees are great for “let me try something” work without committing to a branch name yet:

git worktree add -d ../wt-scratch

Enter fullscreen mode Exit fullscreen mode

If you end up making commits you want to keep, create a branch before you delete the folder so you don’t lose track of them.

A Quick Note on “Why Not Just Clone Twice?”

Separate clones can absolutely solve the same “two directories” problem. The difference is mainly cost and coupling:

  • Clones duplicate setup (another fetch/clone, another .git object store).
  • Worktrees share Git objects, but still behave like separate checkouts.

If you need complete isolation (different remotes, radically different Git config, or you want to move one copy around freely), a second clone can still be the simplest answer.

Keeping Your Directories Sane

The simplest convention (and the one that avoids the “oops, I edited the wrong checkout” mistake) is: keep linked worktrees outside the main project folder.

repo/            # main worktree
repo-hotfix/     # linked worktree
repo-review/     # linked worktree

Enter fullscreen mode Exit fullscreen mode

If you do this often, encode intent in the directory name so it’s searchable later (wt-hotfix-1234, wt-pr-998, wt-bisect-crash) instead of generic tmp/.

If you want all worktrees contained under one parent folder, a popular layout is “bare repo + many worktrees” (see Nick Nisi and Ahmed El Gabri). For background on bare repositories themselves, the Git book chapter is a good reference: Git Basics: Getting a Git Repository.

a conceptual folder layout illustration comparing “sibling worktrees” vs “bare repo + worktrees inside one folder.”

If you try the “bare repo + worktrees” approach, keep the tradeoff in mind: you’re saving Git object duplication, not environment duplication. Two worktrees can still mean two node_modules/ folders, two build outputs, and two IDE indexes. If setup dominates your workflow, keep only the worktrees you’re actively using.

The Lifecycle Gotchas (and the 5 Commands that Prevent Them)

Removing vs Deleting (Stale Metadata)

Deleting a worktree folder in Finder isn’t the same as telling Git it’s gone. Prefer:

git worktree remove ../wt-review

Enter fullscreen mode Exit fullscreen mode

If you already deleted the folder, clean up the leftover admin state:

git worktree prune

Enter fullscreen mode Exit fullscreen mode

Git can also garbage-collect stale worktree metadata automatically over time (controlled by gc.worktreePruneExpire). That’s helpful, but it’s not a substitute for removing worktrees intentionally when you’re done.

Diagram

“This Branch Is Already Checked Out”

This is Git enforcing “one branch per worktree.” Your usual fixes are:

  • make a new branch name (-b)
  • use detached HEAD (-d)

If you’re debugging “why won’t Git let me…”, list the current attachments:

git worktree list

Enter fullscreen mode Exit fullscreen mode

Moving Worktrees (and Repairing when Paths Change)

If you need to reorganize, prefer Git’s commands over dragging folders around in your file manager.

  • git worktree move <worktree> <new-path> relocates a linked worktree (you can’t move the main worktree).
  • If you moved things manually and links broke, git worktree repair can reestablish the connection in supported cases.

Intermittent Drives: Lock Before Git Prunes

If a worktree lives on an external drive or network mount, Git may treat it as “missing” when the volume isn’t mounted. Use git worktree lock to prevent surprises:

git worktree lock --reason "On external drive" /Volumes/SSD/wt-release

Enter fullscreen mode Exit fullscreen mode

Cheat Sheet

git worktree add ../wt-name -b my-branch   # new worktree + new branch
git worktree add ../wt-name origin/branch  # worktree from remote-tracking branch
git worktree add -d ../wt-scratch          # detached-HEAD scratch worktree
git worktree list                          # see what's attached
git worktree remove ../wt-name             # remove cleanly
git worktree prune                         # cleanup after manual deletion

Enter fullscreen mode Exit fullscreen mode

The Takeaway

Worktrees aren’t a niche add-on. They’re the name for the checkout you already use, plus a way to add more checkouts without cloning again. Keep the mental model in your head—shared history, separate working state—and Git’s guardrails (like one branch per worktree) stop feeling arbitrary and start feeling helpful.

If you learned something from this post, give me a follow and checkout the AI powered markdown editor that i am building on the side.