DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

Git worktree? What, Why and When

I recently started using git worktree to see if it solves my pain-point and it does in some scenario. As it takes too long to explain how it works in blog, I just share scenario and you can learn what it is in YouTube videos if you want.

pain point?

While I work on new feature in my branch, I often need to checkout another branch for code review of a pull request.

If I try to checkout to the PR branch, I may fail if I have working file(s).

error: Your local changes to the following files would be overwritten by checkout:
        test.txt
Please commit your changes or stash them before you switch branches.
Aborting
Enter fullscreen mode Exit fullscreen mode

Then, I need to git stash to move my working files into stash stack or, git add/commit to clean my branch.

Why this happens?

This is because git uses same working directory for all branches. This infers if we use separate working directory for branches, we won't encounter file conflict issue.

That's what we often do. We often clone to another directory for PR and keep original directory for our work. But we have to clean it by ourselves, and we need to clearly remember which folder contains which branch changes.

Worktree

In this situation, git worktree does this for us. It creates directory for each branch, but it still works exactly same for git workflows. As it adds additional folders and objects, there are many best practices, as we may not expect others do the same, so we need to fully understand how worktree works. There are many useful videos in YouTube which explains very detail.

References

git worktree doc
Tech Tuesday - Git Worktrees
How to Use Git Worktree | Checkout Multiple Git Branches at Once

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay