GIT... nem tem muito o que falar né. Se você não conhece ou não usa, tem algo muito errado no seu roadmap! Arrisco a dizer que mesmo que você não seja desenvolvedor ou não mexa com código, se você quer ter controle de documentos que vai atualizando com o tempo, o GIT serve para você!
Esta página contém uma lista dos comandos Git mais utilizados para controle de versão, colaboração e gerenciamento de repositórios.
Configuração Inicial #
git config --global user.name "Seu Nome" # Configurar nome do usuário
git config --global user.email "email@exemplo.com" # Configurar email
git config --global init.defaultBranch main # Definir branch padrão
git config --list # Listar todas as configurações
git config user.name # Ver configuração específica
git config --global core.editor "code --wait" # Definir editor padrão
Criação e Clonagem #
git init # Inicializar repositório local
git init nome-projeto # Criar e inicializar diretório
git clone https://github.com/user/repo.git # Clonar repositório remoto
git clone https://github.com/user/repo.git meu-projeto # Clonar com nome personalizado
git clone --depth 1 url # Clone shallow (apenas último commit)
git clone -b branch-name url # Clonar branch específico
Status e Informações #
git status # Status do repositório
git status -s # Status resumido
git log # Histórico de commits
git log --oneline # Log resumido em uma linha
git log --graph # Log com gráfico de branches
git log --author="Nome" # Commits de autor específico
git log --since="2024-01-01" # Commits desde data específica
git log -n 5 # Últimos 5 commits
git show # Mostrar último commit
git show commit-hash # Mostrar commit específico
Staging Area (Área de Preparação) #
git add arquivo.txt # Adicionar arquivo específico
git add . # Adicionar todos os arquivos
git add *.js # Adicionar arquivos por padrão
git add -A # Adicionar todos (incluindo removidos)
git add -p # Adicionar interativamente (por partes)
git reset arquivo.txt # Remover arquivo do staging
git reset # Remover todos do staging
git rm arquivo.txt # Remover arquivo (staged)
git rm --cached arquivo.txt # Remover do staging, manter no disco
Commits #
git commit -m "Mensagem do commit" # Commit com mensagem
git commit -am "Mensagem" # Add e commit em um comando
git commit --amend # Alterar último commit
git commit --amend -m "Nova mensagem" # Alterar mensagem do último commit
git commit --amend --no-edit # Adicionar arquivos ao último commit
git commit --allow-empty -m "Commit vazio" # Commit vazio
Branches (Ramificações) #
git branch # Listar branches locais
git branch -a # Listar todas as branches (local e remoto)
git branch -r # Listar branches remotos
git branch nova-branch # Criar nova branch
git branch -d branch-name # Deletar branch (merged)
git branch -D branch-name # Forçar deleção de branch
git checkout branch-name # Trocar para branch
git checkout -b nova-branch # Criar e trocar para nova branch
git switch branch-name # Trocar branch (Git 2.23+)
git switch -c nova-branch # Criar e trocar (Git 2.23+)
Merge (Fusão) #
git merge branch-name # Fazer merge da branch
git merge --no-ff branch-name # Merge sem fast-forward
git merge --squash branch-name # Merge com squash (um commit)
git merge --abort # Cancelar merge em andamento
Rebase #
git rebase main # Rebase da branch atual com main
git rebase -i HEAD~3 # Rebase interativo dos últimos 3 commits
git rebase --continue # Continuar rebase após resolver conflitos
git rebase --abort # Cancelar rebase
git rebase --skip # Pular commit no rebase
Remotos #
git remote # Listar remotos
git remote -v # Listar remotos com URLs
git remote add origin https://github.com/user/repo.git # Adicionar remoto
git remote remove origin # Remover remoto
git remote rename origin upstream # Renomear remoto
git remote set-url origin nova-url # Alterar URL do remoto
Push e Pull #
git push # Enviar commits para remoto
git push origin main # Enviar para branch específica
git push -u origin main # Enviar e definir upstream
git push --all # Enviar todas as branches
git push --tags # Enviar tags
git push --force # Forçar push (cuidado!)
git pull # Baixar e fazer merge
git pull --rebase # Pull com rebase em vez de merge
git fetch # Baixar sem fazer merge
git fetch origin # Fetch de remoto específico
Desfazendo Mudanças #
git checkout -- arquivo.txt # Desfazer mudanças no arquivo
git checkout . # Desfazer todas as mudanças não-staged
git clean -fd # Remover arquivos não-tracked
git reset --soft HEAD~1 # Desfazer último commit (manter staged)
git reset --mixed HEAD~1 # Desfazer último commit (unstage)
git reset --hard HEAD~1 # Desfazer último commit (perder mudanças)
git revert commit-hash # Reverter commit específico
Stash (Guardar Temporariamente) #
git stash # Guardar mudanças temporariamente
git stash push -m "Mensagem" # Stash com mensagem
git stash list # Listar stashes
git stash pop # Aplicar e remover último stash
git stash apply # Aplicar último stash (manter)
git stash apply stash@{2} # Aplicar stash específico
git stash drop # Remover último stash
git stash clear # Limpar todos os stashes
Diferenças #
git diff # Diferenças não-staged
git diff --staged # Diferenças staged
git diff HEAD # Diferenças desde último commit
git diff branch1 branch2 # Diferenças entre branches
git diff commit1 commit2 # Diferenças entre commits
git diff --name-only # Apenas nomes dos arquivos
git diff --stat # Estatísticas das mudanças
Tags #
git tag # Listar tags
git tag v1.0.0 # Criar tag leve
git tag -a v1.0.0 -m "Versão 1.0.0" # Criar tag anotada
git tag -d v1.0.0 # Deletar tag local
git push origin v1.0.0 # Enviar tag específica
git push origin --tags # Enviar todas as tags
git push origin :refs/tags/v1.0.0 # Deletar tag remota
Pesquisa e Navegação #
git grep "texto" # Buscar texto nos arquivos
git grep -n "função" # Buscar com números de linha
git log --grep="bug" # Buscar commits por mensagem
git log -S "função" # Buscar commits que adicionaram/removeram texto
git blame arquivo.txt # Ver quem modificou cada linha
git bisect start # Iniciar bisect para encontrar bug
git bisect good commit-hash # Marcar commit como bom
git bisect bad commit-hash # Marcar commit como ruim
Aliases Úteis #
git config --global alias.st status # Criar alias 'st' para status
git config --global alias.co checkout # Alias 'co' para checkout
git config --global alias.br branch # Alias 'br' para branch
git config --global alias.ci commit # Alias 'ci' para commit
git config --global alias.unstage 'reset HEAD --' # Alias para unstage
git config --global alias.last 'log -1 HEAD' # Alias para último commit
git config --global alias.visual '!gitk' # Alias para interface gráfica
Workflow GitFlow #
# Feature branches
git checkout -b feature/nova-funcionalidade
git push -u origin feature/nova-funcionalidade
# Release branches
git checkout -b release/v1.2.0
git push -u origin release/v1.2.0
# Hotfix branches
git checkout -b hotfix/correcao-urgente
git push -u origin hotfix/correcao-urgente
Colaboração #
# Fork workflow
git remote add upstream https://github.com/original/repo.git
git fetch upstream
git merge upstream/main
# Pull Request workflow
git checkout -b feature/minha-feature
git push -u origin feature/minha-feature
# Criar PR via interface web
# Sync with upstream
git fetch upstream
git checkout main
git merge upstream/main
git push origin main
Resolução de Conflitos #
# Durante merge/rebase
git status # Ver arquivos em conflito
# Editar arquivos para resolver conflitos
git add arquivo-resolvido.txt # Marcar como resolvido
git commit # Finalizar merge
# ou
git rebase --continue # Continuar rebase
# Ferramentas de merge
git mergetool # Abrir ferramenta de merge
git config --global merge.tool vimdiff # Configurar ferramenta
Histórico e Reflog #
git reflog # Log de referências (histórico completo)
git reflog show branch-name # Reflog de branch específica
git reset --hard HEAD@{2} # Voltar para estado específico do reflog
git log --follow arquivo.txt # Histórico de arquivo (mesmo renomeado)
git log --patch arquivo.txt # Mudanças em arquivo específico
Cherry-pick #
git cherry-pick commit-hash # Aplicar commit específico
git cherry-pick commit1 commit2 # Aplicar múltiplos commits
git cherry-pick --no-commit commit-hash # Cherry-pick sem fazer commit
git cherry-pick --continue # Continuar após resolver conflitos
git cherry-pick --abort # Cancelar cherry-pick
Submodules #
git submodule add https://github.com/user/repo.git path # Adicionar submodule
git submodule init # Inicializar submodules
git submodule update # Atualizar submodules
git submodule update --remote # Atualizar para último commit
git clone --recurse-submodules url # Clonar com submodules
Worktrees #
git worktree add ../projeto-feature feature # Criar worktree para branch
git worktree list # Listar worktrees
git worktree remove ../projeto-feature # Remover worktree
git worktree prune # Limpar referências de worktrees
Arquivos .gitignore #
# Exemplos comuns para .gitignore
*.log # Ignorar arquivos .log
node_modules/ # Ignorar diretório
.env # Arquivos de ambiente
*.tmp # Arquivos temporários
!importante.log # Exceção (não ignorar)
# Aplicar .gitignore a arquivos já tracked
git rm --cached arquivo.txt
git commit -m "Remove arquivo do tracking"
Hooks #
# Hooks comuns (em .git/hooks/)
pre-commit # Executar antes do commit
post-commit # Executar após commit
pre-push # Executar antes do push
pre-receive # No servidor, antes de receber
# Exemplo de pre-commit hook
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
echo "Testes falharam, commit cancelado"
exit 1
fi
Debugging e Manutenção #
git fsck # Verificar integridade do repositório
git gc # Garbage collection
git gc --aggressive # Garbage collection agressivo
git count-objects -v # Estatísticas do repositório
git rev-list --objects --all | sort -k 2 # Arquivos por tamanho
Casos Práticos #
Corrigir Último Commit #
# Adicionar arquivo esquecido
git add arquivo-esquecido.txt
git commit --amend --no-edit
# Alterar mensagem do último commit
git commit --amend -m "Nova mensagem corrigida"
Desfazer Commits #
# Desfazer último commit mantendo mudanças
git reset --soft HEAD~1
# Desfazer últimos 3 commits perdendo mudanças
git reset --hard HEAD~3
# Reverter commit público
git revert commit-hash
Limpar Histórico #
# Squash últimos 3 commits
git rebase -i HEAD~3
# No editor: mudar 'pick' para 'squash' nos commits
# Remover arquivo de todo histórico
git filter-branch --tree-filter 'rm -f arquivo-sensivel.txt' HEAD
# ou com git filter-repo (mais moderno)
git filter-repo --path arquivo-sensivel.txt --invert-paths
Sincronização #
# Sync branch com main
git checkout main
git pull origin main
git checkout minha-branch
git rebase main
# Atualizar fork
git remote add upstream https://github.com/original/repo.git
git fetch upstream
git checkout main
git merge upstream/main
git push origin main
Release #
# Criar release
git checkout main
git pull origin main
git tag -a v1.2.0 -m "Release v1.2.0"
git push origin v1.2.0
# Hotfix para release
git checkout v1.2.0
git checkout -b hotfix/v1.2.1
# Fazer correções
git tag -a v1.2.1 -m "Hotfix v1.2.1"
git push origin v1.2.1
Configurações Avançadas #
Configurações Globais Úteis #
# Melhorar output dos comandos
git config --global color.ui auto
git config --global core.pager "less -FRSX"
# Configurar merge/diff tools
git config --global merge.tool vscode
git config --global diff.tool vscode
# Auto-correção de comandos
git config --global help.autocorrect 1
# Rebase por padrão no pull
git config --global pull.rebase true
SSH e Autenticação #
# Gerar chave SSH
ssh-keygen -t ed25519 -C "email@exemplo.com"
# Testar conexão SSH
ssh -T git@github.com
# Usar SSH em vez de HTTPS
git remote set-url origin git@github.com:user/repo.git
Scripts e Automação #
Script de Deploy #
#!/bin/bash
# deploy.sh
echo "Fazendo deploy..."
git checkout main
git pull origin main
npm install
npm run build
git tag -a "v$(date +%Y%m%d%H%M)" -m "Deploy $(date)"
git push origin --tags
echo "Deploy concluído!"
Script de Backup #
#!/bin/bash
# backup-repo.sh
REPO_DIR="/caminho/para/repo"
BACKUP_DIR="/backup/git-repos"
DATE=$(date +%Y%m%d_%H%M%S)
cd $REPO_DIR
git bundle create "$BACKUP_DIR/repo-backup-$DATE.bundle" --all
echo "Backup criado: repo-backup-$DATE.bundle"
Cleanup Script #
#!/bin/bash
# cleanup.sh
echo "Limpando branches merged..."
git branch --merged main | grep -v "main\|master" | xargs -n 1 git branch -d
echo "Limpando branches remotas removidas..."
git remote prune origin
echo "Garbage collection..."
git gc --prune=now
Troubleshooting Comum #
Problemas Frequentes #
# "fatal: refusing to merge unrelated histories"
git pull origin main --allow-unrelated-histories
# Reverter merge problemático
git merge --abort
# Arquivo muito grande
git rm --cached arquivo-grande.bin
echo "arquivo-grande.bin" >> .gitignore
# Push rejeitado
git pull --rebase origin main
git push origin main
Performance #
# Otimizar repositório grande
git repack -ad
git prune-packed
git gc --aggressive
# Verificar tamanho do repositório
du -sh .git/
# Clone shallow para repositórios grandes
git clone --depth 1 --single-branch url
Melhores Práticas #
Commits #
- Use mensagens descritivas e no imperativo
- Faça commits pequenos e focados
- Use conventional commits quando apropriado
Branches #
- Use nomes descritivos (feature/login, bugfix/header-css)
- Mantenha branches atualizadas com main
- Delete branches após merge
Colaboração #
- Sempre faça pull antes de push
- Use pull requests para revisão de código
- Resolva conflitos localmente antes de push
Segurança #
- Nunca commite senhas ou tokens
- Use .gitignore adequadamente
- Revise mudanças antes de commit