Exemplos práticos de copiar e colar para o fluxo de trabalho diário com worktree: criar, fazer checkout, mesclar, buscar e remover. Todos os comandos assumem um Git recente (2.23+) para que git switch funcione ao lado do mais antigo git checkout.
Cartão de referência rápida -- pronto para copiar e colar.
# Create + checkout an existing branch in a new worktreegit worktree add ../feature-branch feature-branch# Create a new branch and check it out in a new worktreegit worktree add ../new-feature -b new-feature# Detached HEAD on a specific commit or taggit worktree add ../hotfix abc1234# List worktrees and the branch each one has checked outgit worktree list# Remove a worktree once you're donegit worktree remove ../feature-branch# Clean up stale entries after a folder was deleted manuallygit worktree prune
Quando usar isso: Qualquer fluxo de trabalho baseado em worktree -- desenvolvimento de features, isolamento de hotfixes, revisão de PR, comparação lado a lado.
# 1. Start the feature in a new worktree on a new branchgit worktree add ../my-feature -b my-feature# 2. Move into it and work normallycd ../my-feature# ...edit files, run tests, commit...git add .git commit -m "feat: scaffold my-feature"# 3. Walk back to main and mergecd ../main-repogit switch maingit pull origin maingit merge my-feature# 4. Push and clean upgit push origin maingit worktree remove ../my-featuregit branch -d my-feature
O que isso demonstra:
Worktrees e branches compartilham o histórico imediatamente -- nenhum ciclo de push/pull é necessário entre eles.
A mesclagem ocorre no worktree de destino (aquele cujo branch receberá as alterações).
Remover um worktree deixa o branch intacto; excluir o branch é um passo separado e deliberado.
# Create a new worktree and checkout an existing branchgit worktree add ../feature-branch feature-branch# Create a new branch AND check it out in a new worktreegit worktree add ../new-feature -b new-feature# Checkout a specific commit or tag (detached HEAD)git worktree add ../hotfix abc1234# Modern alternative to git checkout (safer for branches)git switch <branch> # Inside a worktreegit switch -c <new-branch> # Create + switch
Dica: Prefira git switch em vez de git checkout para operações de branch (introduzido no Git 2.23+). git checkout ainda funciona, mas é sobrecarregado com comportamento de restauração de arquivos, o que pode ser problemático se você digitar incorretamente um nome de branch.
git branch -a # All branches (local + remote)git branch -v # With last commit infogit worktree list # Which branch each worktree has checked outgit worktree list --porcelain # Machine-readable for scripts
git worktree list é a resposta para "espere, onde eu deixei aquele hotfix?"
A mesclagem ocorre no worktree de destino -- geralmente aquele com main ou um branch de release em checkout.
# From your main worktree:cd ../main-projectgit switch main # or: git checkout maingit pull origin main # Always update first# Merge a completed feature branch (developed in another worktree)git merge feature-branch # Fast-forward or create a merge commit# Merge with optionsgit merge --no-ff feature-branch # Always create a merge commitgit merge --squash feature-branch # Squash changes (then commit manually)# Rebase instead, for a cleaner historygit switch feature-branch # Switch into the feature branch's worktree firstgit rebase maingit switch maingit merge feature-branch # Now a clean fast-forward
Exemplo de mesclagem entre worktrees:
Termine o trabalho e comite dentro de ../feature-worktree.
Volte para o worktree principal com cd.
git merge feature-branch -- o ponteiro do branch foi atualizado automaticamente pelo commit no outro worktree.
Sem push, sem pull, sem viagem de ida e volta ao remoto. A pasta .git compartilhada torna isso transparente.
git fetch origin # Updates remote refs -- visible from all worktreesgit pull origin main # Fetch + merge into the worktree you ran this in# Update a feature worktree's basecd ../my-featuregit fetch origingit rebase origin/main # Replay your feature commits on top of latest main
Ponto chave:git fetch atualiza o estado na pasta .git compartilhada, então cada worktree vê as novas refs remotas imediatamente. git pull afeta apenas o branch em checkout no worktree onde você o executou.
# You're deep in feature work in ../my-feature, and prod breaks.# Don't stash. Don't switch branches. Just spin up a hotfix worktree.cd ~/projects/main-repogit fetch origingit worktree add ../hotfix -b hotfix/login-500 origin/maincd ../hotfix# ...debug, fix, commit, push, open PR...git push -u origin hotfix/login-500# Once the PR is merged, clean upcd ~/projects/main-repogit worktree remove ../hotfixgit branch -D hotfix/login-500 # If the remote branch was deleted on merge# Walk back to your feature work, exactly as you left itcd ../my-feature
# A teammate pushed a branch you need to reviewgit fetch origingit worktree add ../review-pr-482 origin/feature/teammate-thingcd ../review-pr-482npm installnpm run dev# ...read code, test it, leave PR comments...# Tear it down when donecd ../main-repogit worktree remove ../review-pr-482
# Run two implementations at once for a real comparisongit worktree add ../approach-a -b experiment/approach-agit worktree add ../approach-b -b experiment/approach-b# Two terminal windows, two dev servers on different ports, both editable.# When done, keep the winner, remove the loser.git worktree remove ../approach-bgit branch -D experiment/approach-b
Coisas que vão te morder. Cada armadilha inclui o que dá errado, por que acontece e a correção.
fatal: '<branch>' is already checked out at ... -- Você tentou adicionar um worktree em um branch que já está em checkout em outro lugar. Correção: Ou trabalhe no worktree existente, ou crie um novo branch a partir dele: git worktree add ../scratch -b scratch <branch>.
Conflitos de rebase em um worktree de feature, e depois esquecer de atualizar o alvo da mesclagem -- Você fez rebase de feature em origin/main dentro de ../my-feature, mas no seu worktree principal você esqueceu de executar git pull primeiro. Correção: Sempre execute git fetch + git pull no worktree de destino antes de mesclar.
git checkout <branch> altera arquivos no worktree atual -- Você pretendia adicionar um worktree, mas digitou o comando antigo. Correção: Use git worktree add para criar um novo worktree; git switch/git checkout apenas muda o atual.
Stashes se aplicam entre worktrees e te surpreendem -- Você usou stash no worktree A, depois git stash pop no worktree B aplica os arquivos errados. Correção: Stashes são compartilhados. Nomeie-os (git stash push -m "feature X wip") e revise com git stash list antes de usar pop.
Force-push de um branch de um worktree quebra mesclagens em outro -- Worktree A faz force-push de feature, worktree B ainda tem os commits antigos em checkout e um git pull aciona uma recusa confusa de fast-forward. Correção: Coordene force-pushes; execute novamente git fetch + git reset --hard origin/feature no outro worktree se tiver certeza.
node_modules fora de sincronia entre worktrees -- Você atualizou uma dependência no worktree A; o worktree B ainda tem a versão antiga instalada. Correção: Execute npm install (ou seu equivalente) novamente para cada worktree após alterações de dependência.
Commit de merge vai para o branch errado -- Você executou git merge feature-branch de um worktree que tinha develop em checkout, não main. Correção: Execute git branch --show-current antes de mesclar. Use git reset --hard ORIG_HEAD para desfazer a mesclagem se ela ainda não foi enviada.
O Git cria um HEAD destacado por padrão. Para rastrear o branch remoto como um local, use -b: git worktree add ../review -b feature/teammate-branch origin/feature/teammate-branch.
Qual é a diferença entre `git switch` e `git checkout` em um worktree?
Ambos funcionam. git switch foi adicionado no Git 2.23+ para esclarecer a intenção (apenas branches).
git checkout é sobrecarregado -- ele alterna branches e restaura arquivos. Um erro de digitação pode sobrescrever alterações não commitadas.
Dentro de um worktree, prefira git switch <branch> para operações de branch e git restore <arquivo> para operações de arquivo.
Posso executar `git pull` em um worktree e ele afetar os outros?
git pull apenas faz fast-forward ou mescla o branch em checkout no worktree onde você o executou.
As refs remotas buscadas (origin/main, etc.) tornam-se visíveis em todos os worktrees, mas os ponteiros de branch locais em outros worktrees não se movem automaticamente.
Como faço rebase de um worktree de feature no main mais recente?
cd ../my-featuregit fetch origingit rebase origin/main
git fetch atualiza a ref remota. git rebase origin/main reaplica seus commits de feature no topo.
Se você tiver commits locais para enviar depois, precisará de git push --force-with-lease (nunca git push --force simples).
O que acontece se eu executar `git merge feature-branch` do worktree errado?
O commit de merge vai para o branch que o worktree atual tem em checkout, o que pode não ser o que você queria.
Execute git branch --show-current antes de mesclar para evitar isso.
Se você ainda não enviou, git reset --hard ORIG_HEAD desfaz a mesclagem de forma limpa.
Posso fazer cherry-pick de um commit do branch de outro worktree?
git cherry-pick <sha>
Sim. O commit vive na pasta .git compartilhada, então cherry-pick funciona entre worktrees sem sintaxe especial.
Se o SHA estiver em um branch que você nunca buscou, execute git fetch primeiro.
Como comparo dois branches em checkout em worktrees diferentes?