Advanced Git Techniques
Table of Contents
Interactive Rebase
Interactive rebase lets you edit, reorder, squash, or drop commits.
git rebase -i HEAD~5
When the editor opens, you’ll see a list of the last five commits. Use the commands:
pick– keep the commit as‑isreword– edit the commit messageedit– amend the commitsquash– combine with the previous commitdrop– remove the commit
After saving and exiting, Git will apply the changes. Resolve any conflicts before continuing with git rebase --continue.
Rewrite History Safely
Never rewrite public history. For private branches, you can use filter-branch or the faster filter-repo tool.
# Remove a file from all history
git filter-repo --path filename.txt --invert-paths
After rewriting, force‑push the branch:
git push --force-with-lease origin my-branch
Use --force-with-lease to protect against overwriting others' work.
Advanced Merge Strategies
Git offers several built‑in strategies. The most common are:
recursive– default, handles most cases.ours– keep current branch’s content.theirs– keep incoming branch’s content (via-X theirs).octopus– merge more than two branches at once.
Example of a strategy option:
git merge feature-branch -X ours
For complex merges, consider git rerere to record conflict resolutions:
git config --global rerere.enabled true
Managing Submodules
Submodules let you embed other Git repos:
# Add a submodule
git submodule add https://github.com/example/lib.git external/lib
# Clone a repo with submodules
git clone --recurse-submodules https://github.com/user/project.git
# Update submodules
git submodule update --remote --merge
When branching, remember to commit submodule pointer changes.
Custom Git Hooks
Hooks automate tasks. Place executable scripts in .git/hooks.
# .git/hooks/pre-commit (example)
#!/bin/sh
# Prevent committing large files >5 MB
if git diff --cached --name-only | while read f; do
[ $(stat -c%s "$f") -gt $((5*1024*1024)) ] && echo "$f is too large"
fi; then
echo "Commit aborted."
exit 1
fi
Make the hook executable:
chmod +x .git/hooks/pre-commit
Performance Tuning
Speed up large repos with these settings:
# Reduce pack size for faster cloning
git config --global pack.windowMemory "100m"
git config --global pack.packSizeLimit "100m"
# Enable shallow clones when history isn’t needed
git clone --depth 1 https://github.com/user/big-repo.git
Use git gc --aggressive occasionally to prune unreachable objects.
Automation with Git Aliases
Add shortcuts to your global config:
git config --global alias.lg "log --graph --oneline --decorate"
git config --global alias.unstage "reset HEAD --"
git config --global alias.amend "commit --amend --no-edit"
Now you can run git lg to see a concise visual log.