Utilitários Git
Ferramentas poderosas para situações do dia a dia - salvar trabalho em andamento, encontrar commits que introduziram bugs, mover commits entre branches e se recuperar de erros.
Busque em todas as páginas da documentação
Ferramentas poderosas para situações do dia a dia - salvar trabalho em andamento, encontrar commits que introduziram bugs, mover commits entre branches e se recuperar de erros.
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥
Cartão de referência rápida - pronto para copiar e colar.
# Stash current changes
git stash
git stash pop
# Cherry-pick a commit from another branch
git cherry-pick abc1234
# Find the commit that introduced a bug
git bisect start
git bisect bad # current commit is broken
git bisect good v1.0.0 # this tag was working
# Git checks out commits for you to test, then:
git bisect good # or git bisect bad
git bisect reset # when done
# Recover a lost commit
git reflog
git checkout -b recovery abc1234Quando usar isso: Quando add/commit/branch básicos não são suficientes - troca de contexto, depuração de regressões, movimentação de commits específicos ou recuperação de erros.
# You're mid-feature but need to fix a bug on main
git stash -m "WIP: dashboard chart component"
git checkout main
git checkout -b hotfix/login-error
# ... fix the bug, commit, push, merge ...
git checkout feature/dashboard
git stash pop
# Back to your WIP exactly where you left offO que isso demonstra:
-m facilitam a identificação posteriorstash pop aplica e remove o stash em uma única etapa# A teammate fixed a utility function on their branch
# You need just that one commit, not their whole branch
git cherry-pick abc1234
# Cherry-pick without committing (stage changes only)
git cherry-pick --no-commit abc1234
# Cherry-pick a range of commits
git cherry-pick abc1234..def5678O que isso demonstra:
--no-commit permite modificar as alterações antes de comitar# Stash including untracked files
git stash -u
# Stash including ignored files
git stash -a
# List all stashes
git stash list
# stash@{0}: On feature/dashboard: WIP: chart component
# stash@{1}: On main: quick experiment
# Apply a specific stash (keep it in the list)
git stash apply stash@{1}
# Drop a specific stash
git stash drop stash@{1}
# Clear all stashes
git stash clear
# Create a branch from a stash
git stash branch new-feature stash@{0}
# Show what's in a stash
git stash show -p stash@{0}git bisect executa uma busca binária no histórico de commits para encontrar exatamente qual commit introduziu um bug.
# Manual bisect
git bisect start
git bisect bad # HEAD is broken
git bisect good abc1234 # this commit was working
# Git checks out a commit halfway between good and bad
# Test it, then tell Git:
git bisect good # this commit works fine
# or
git bisect bad # this commit is broken
# Repeat until Git finds the first bad commit
# "abc1234 is the first bad commit"
git bisect reset # return to your original branch
# Automated bisect with a test script
git bisect start HEAD abc1234
git bisect run npm test
# Git automatically runs the test at each step
# Exit code 0 = good, non-zero = badO reflog registra cada vez que o HEAD se move. É o seu histórico de desfazer para o próprio Git.
# View reflog
git reflog
# abc1234 HEAD@{0}: commit: feat: add search
# def5678 HEAD@{1}: rebase (finish): returning to refs/heads/feature
# ghi9012 HEAD@{2}: rebase (start): checkout main
# jkl3456 HEAD@{3}: commit: feat: add dashboard
# Recover after a bad rebase
git reflog
# Find the commit hash before the rebase started
git reset --hard HEAD@{3}
# Recover a deleted branch
git reflog
# Find the last commit on the deleted branch
git checkout -b recovered-branch abc1234# Preview what would be removed (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files and directories
git clean -fd
# Remove ignored files too (full reset)
git clean -fdx
# Interactive mode
git clean -i# Create a lightweight tag
git tag v1.0.0
# Create an annotated tag (recommended for releases)
git tag -a v1.0.0 -m "Release version 1.0.0"
# Tag a specific commit
git tag -a v0.9.0 abc1234 -m "Beta release"
# List tags
git tag -l
git tag -l "v1.*"
# Push tags to remote
git push origin v1.0.0
git push origin --tags
# Delete a tag
git tag -d v1.0.0
git push origin --delete v1.0.0# Reset - move HEAD backward (rewrites history)
git reset --soft HEAD~1 # undo commit, keep changes staged
git reset --mixed HEAD~1 # undo commit, keep changes unstaged (default)
git reset --hard HEAD~1 # undo commit, discard changes entirely
# Revert - create a new commit that undoes a previous one (safe for shared branches)
git revert abc1234
git revert HEAD~3..HEAD # revert a range
git revert --no-commit abc1234 # stage the revert without committingRegra geral: Use reset em commits locais/não enviados. Use revert em commits compartilhados/enviados.
# Create a worktree for a different branch
git worktree add ../project-hotfix hotfix/login-error
# List worktrees
git worktree list
# Remove a worktree when done
git worktree remove ../project-hotfixWorktrees permitem que você tenha múltiplos branches extraídos simultaneamente em diretórios separados - sem necessidade de stash.
Coisas que vão te morder. Cada armadilha inclui o que dá errado, por que acontece e a correção.
stash pop com conflitos - git stash pop tenta aplicar e remover o stash. Se houver conflitos, o stash NÃO é removido. Correção: Resolva os conflitos, então execute git stash drop manualmente.
cherry-pick cria commits duplicados - O commit selecionado recebe um novo hash. Se o branch de origem for mesclado posteriormente, você terá duas cópias. Correção: Isso geralmente é inofensivo - o Git lida com isso durante a mesclagem. Mas para limpeza, considere usar rebase em vez disso.
reset --hard perde trabalho não commitado - Não há como recuperar alterações não preparadas após git reset --hard. Correção: Sempre execute git stash antes de fazer um reset hard. Ou use git reset --soft para manter as alterações.
bisect esquecendo de resetar - Você termina o bisect, mas esquece git bisect reset e permanece em um HEAD desanexado. Correção: Execute git bisect reset para retornar ao seu branch.
clean removendo arquivos necessários - git clean -fdx exclui tudo o que não é rastreado, incluindo arquivos .env. Correção: Sempre execute um dry run primeiro com git clean -n.
Outras maneiras de resolver o mesmo problema - e quando cada uma é a melhor escolha.
| Alternativa | Use Quando | Não Use Quando |
|---|---|---|
git stash vs comitar WIP | Troca rápida de contexto, voltando em breve | Deixar o WIP por dias - comite em um branch |
git revert vs git reset | O commit já foi enviado/compartilhado | Commits apenas locais onde reset é mais limpo |
git cherry-pick vs git rebase | Você precisa de um ou dois commits específicos | Você precisa das alterações de um branch inteiro |
git worktree vs git stash | Trabalho paralelo de longa duração em dois branches | Troca rápida de branch pontual |
pop aplica o stash e o remove da lista de stashesapply aplica o stash, mas o mantém na listaapply quando quiser aplicar o mesmo stash em múltiplos branchesgit stash push -m "partial stash" src/components/Button.tsxgood ou bad e o Git o reduz em O(log n) passosgit bisect start HEAD v1.0.0
git bisect run npm testpop encontra um conflito de mesclagem, ele aplica o stash, mas não o removegit stash dropgit reflog
# Find the last commit hash on the deleted branch
git checkout -b recovered-branch abc1234reset move o HEAD para trás, reescrevendo o histórico (use em commits locais/não enviados)revert cria um novo commit que desfaz um anterior (seguro para branches compartilhados)-x remove arquivos ignorados por .gitignore, incluindo .envgit clean -n (dry run) primeiro para pré-visualizar o que será excluídogit worktree add ../project-hotfix hotfix/login-error
# Work in ../project-hotfix independently
git worktree remove ../project-hotfixgit tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0-a) para lançamentos, pois elas armazenam autor, data e mensagemnpm version para atualizar package.json automaticamenteRevisado por Chris St. John·Última atualização: 19 de jul. de 2026
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥