🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

Git Stash: guia completo – Salvar, aplicar, abrir, descartar e ramificar do Stash

⏱️5 min read  ·  1,045 words

git stashsalva temporariamente as alterações do diretório de trabalho para que você possa alternar o contexto sem comprometer trabalho incompleto. É um dos comandos Git mais úteis, mas subutilizados. Este guia cobre cada subcomando com exemplos práticos.

Conceito Central

# You're in the middle of feature work and need to switch branches
git status
# M  src/auth.ts    ← modified
# M  src/utils.ts   ← modified
# ?? src/new-file.ts  ← untracked

git checkout main  # ERROR: would overwrite changes

# git stash saves and cleans your working directory
git stash
# Saved working directory and index state WIP on feature: abc123 Add auth

git checkout main  # ✅ now clean working tree

# ... do what you needed on main ...

git checkout feature
git stash pop      # restore your changes

Comandos git stash

# Save stash with a message (recommended — harder to forget what it was)
git stash push -m "WIP: auth middleware refactor"

# Short form (saves tracked changes only)
git stash

# Include untracked files
git stash push --include-untracked   # or -u

# Include untracked AND ignored files (rare)
git stash push --all                 # or -a

# Partial stash — choose specific files
git stash push -m "just auth changes" -- src/auth.ts src/auth.test.ts

Listagem e inspeção de estoques

# List all stashes
git stash list
# stash@{0}: WIP on feature: abc123 Add auth
# stash@{1}: WIP on main: def456 Fix bug
# stash@{2}: On feature: Manual save before experiment

# Show what's in a stash (summary)
git stash show            # most recent
git stash show stash@{1} # specific stash

# Show full diff of a stash
git stash show -p stash@{0}

Restaurando: pop vs apply

# git stash pop — apply AND remove from stash list
git stash pop              # applies stash@{0} and removes it
git stash pop stash@{2}   # apply a specific stash

# git stash apply — apply but KEEP in stash list
git stash apply            # applies stash@{0}, keeps it in list
git stash apply stash@{1}

# When to use apply:
# - When you want to apply the same stash to multiple branches
# - When you're not sure the apply will be clean and want to retry
# - As a safety measure — you can always drop manually after

Conflitos ao aplicar Stash

# If the stash conflicts with current branch state:
git stash pop
# CONFLICT (content): Merge conflict in src/auth.ts
# The stash entry is NOT removed when conflicts occur

# Fix conflicts normally
git add src/auth.ts
git stash drop    # manually remove the stash after resolving
# (pop would have removed it automatically if no conflicts)

Ramificação de um Stash

# Create a new branch FROM the commit where the stash was saved
# and apply the stash to it — useful when stash won't apply cleanly to current branch
git stash branch my-new-branch stash@{0}

# This is equivalent to:
# git checkout -b my-new-branch stash-parent-commit
# git stash apply stash@{0}
# git stash drop stash@{0}

Removendo esconderijos

# Remove specific stash
git stash drop stash@{0}

# Remove most recent stash
git stash drop

# Remove ALL stashes (dangerous — no undo)
git stash clear

Stash Parcial com Modo Interativo

# Interactively choose which hunks to stash (like git add -p)
git stash push --patch    # or -p

# Shows each changed hunk and asks: stash this hunk? (y/n/d/a/e/?)
# Useful when a file has changes you want to stash and changes you want to keep

Fluxos de trabalho comuns para desenvolvedores

# Workflow 1: Quick context switch
git stash push -m "WIP: new feature"
git checkout main
git pull origin main
# ... fix urgent bug ...
git checkout feature
git stash pop

# Workflow 2: Stash before risky rebase
git stash push -u -m "Before rebase backup"
git rebase origin/main
# If rebase goes wrong: git stash pop restores your state
# (though git reflog is better for full recovery)

# Workflow 3: Test clean build
git stash push -u          # stash everything including untracked
npm run build              # verify clean build works
git stash pop              # restore your work

# Workflow 4: Apply stash to different branch
git stash push -m "shared config changes"
git checkout feature-a
git stash apply stash@{0}  # apply (keep in list)
git checkout feature-b
git stash apply stash@{0}  # apply to second branch too
git stash drop stash@{0}   # now drop it

git stash vs git commit –amend vs git worktree

Cenário Melhor ferramenta
Troca rápida de contexto (mesma máquina, 5-30 min) git stash
Trabalhar em duas filiais simultaneamente git worktree add
Economize WIP com capacidade de enviar para remoto git commit -m "WIP" (conserto mais tarde)
Desfaça o último commit, mas mantenha as alterações git reset HEAD~1

Perguntas Frequentes

P: O git stash funciona em filiais?
R: Sim. Stash é uma pilha global – não específica de branch. Você pode armazenar no ramo A, mudar para o ramo B e colocar o esconderijo lá. Se os arquivos entrarem em conflito com a ramificação B, você terá um conflito de mesclagem para resolver.

P: O git stash salvará arquivos não rastreados?
R: Não por padrão. Usargit stash push -u (ou--include-untracked) para incluir novos arquivos não rastreados. Usargit stash push -a (ou--all) para incluir arquivos não rastreados e gitignored.

P: Deixei cair acidentalmente meu estoque – posso recuperá-lo?
R: Possivelmente. Corregit fsck --no-reflog | awk '/dangling commit/ {print $3}' para encontrar commits pendentes. Entãogit show <hash> para identificar o conteúdo do seu stash egit stash apply <hash> para restaurá-lo. Funciona cerca de 30 dias antes da coleta de lixo do Git.

P: Quantos esconderijos posso ter?
R: Sem limite prático. Mas se você tiver mais de 10 stashes, considere comprometer o WIP ou usar git worktree — uma longa lista de stashes é um sinal de decisões adiadas.

P: Posso armazenar apenas alterações preparadas?
R: Sim:git stash push --staged armazena apenas o que está no índice (preparado), deixando alterações não preparadas no diretório de trabalho. Útil para separar alterações em unidades lógicas menores.

Conclusão

git stash é essencial para uma troca limpa de contexto sem comprometer trabalho incompleto. Os comandos principais:git stash push -u -m "description" salvar (incluindo não rastreado),git stash pop para restaurar e remover,git stash apply para restaurar e manter. Usargit stash branch quando o stash não for aplicado corretamente ao seu branch atual. O stash é uma pilha LIFO – mantenha-o ativamente, descarte os stashes que você não precisa mais e não deixe que ele se acumule além de 3-4 entradas.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা