Ever feel like you’re just scratching the surface of Git? You know the basics – push, pull, commit – but there’s so much more under the hood. Let me show you some tricks that’ll make you go “Wait, Git can do that?!”
1. Selective Staging (Interactive Add)
The Problem: You’ve been coding for hours and made multiple changes to a file, but they should really be in separate commits.
The Solution: git add -p
(The ‘p’ is for ‘patch’)
git add -p
Think of it like organizing your groceries at checkout – you can sort items into different bags (commits) instead of throwing everything together!
When to use it:
- Working on multiple features in one file
- Fixing bugs while adding features
- Code review cleanup
Pro moves:
# View changes before staging git diff # Stage specific lines git add -p y # Yes, stage this chunk n # No, skip this chunk s # Split into smaller chunks ? # Show all options
2. The Undo Button (Reset Last Commit)
The Problem: “Oh no, I just committed that and it’s totally wrong!”
The Solution: git reset --soft HEAD~1
# Keep changes but undo commit git reset --soft HEAD~1 # ⚠️ Nuclear option: undo everything git reset --hard HEAD~1
Think of --soft
like putting ingredients back in the bowl – you can still cook with them. --hard
is like throwing everything in the trash!
When to use it:
- Committed to wrong branch
- Need to add more files
- Want to rewrite commit message
Safety first:
# Create backup branch before resetting git branch backup-branch # Check what you're about to undo git log -1
3. Branch Spring Cleaning (Fetch and Prune)
The Problem: Your branch list looks like a phone book from 1995 – full of outdated entries.
The Solution: git fetch --all --prune
# Update and clean in one go git fetch --all --prune # See what's been cleaned git remote prune origin --dry-run
It’s like having a smart closet that removes clothes you haven’t worn in months!
Best practices:
# First, list all branches git branch -a # After pruning, verify cleanup git branch -a # Remove local branches that are gone remotely git remote prune origin
4. The Quick Fix (Amend Commit)
The Problem: You just committed but forgot something small (we’ve all been there!)
The Solution: git commit --amend
# Fix just the message git commit --amend -m "New message" # Add forgotten file without changing message git add forgotten-file.js git commit --amend --no-edit
It’s like having an edit button for your last text message!
Common uses:
# Add file and change message git add file.js git commit --amend -m "Better message" # Update author info git commit --amend --author="Jane Doe <jane@example.com>" # Update commit date git commit --amend --date="now"
5. The Save Point (Stash)
The Problem: Your boss needs an urgent fix, but you’re mid-feature and not ready to commit.
The Solution: git stash
# Quick save git stash # Save with description git stash save "Working on login feature"
It’s like pressing pause on your game – everything’s saved exactly as you left it!
Power moves:
# List all stashes git stash list # See what's in a stash git stash show stash@{0} # Apply specific stash git stash apply stash@{1} # Create branch from stash git stash branch new-feature stash@{0}
6. Restore Your Work (Stash Pop)
The Problem: You need your stashed changes back, but there are multiple stashes.
The Solution: git stash pop
# Get back last stashed changes git stash pop # Pop specific stash git stash pop stash@{2}
Think of it like retrieving items from your locker – you can take out exactly what you need!
Advanced usage:
# Apply without removing from stash git stash apply # Remove specific stash git stash drop stash@{1} # Clear all stashes (⚠️ use with caution) git stash clear
7. Cherry-Pick Magic (Select Commits)
The Problem: You need that one brilliant fix from another branch, but don’t want the rest.
The Solution: git cherry-pick <commit-hash>
# Pick single commit git cherry-pick abc123 # Pick multiple commits git cherry-pick abc123 def456 # Pick without committing git cherry-pick -n abc123
It’s like picking specific songs for your playlist instead of taking the whole album!
Pro techniques:
# Pick commit and edit message git cherry-pick -e abc123 # Skip commit if it's already applied git cherry-pick --skip # Abort cherry-pick if things go wrong git cherry-pick --abort
8. Branch Cleanup (Delete Branches)
The Problem: Your branch list is longer than your grocery list.
The Solution: git branch -d <branch-name>
# Safe delete (only if merged) git branch -d old-feature # Force delete (⚠️ even if not merged) git branch -D abandoned-feature
Think of it as decluttering your workspace – sometimes you need to let go!
Cleanup strategies:
# List merged branches git branch --merged # Delete all merged branches (except current) git branch --merged | grep -v "\*" | xargs -n 1 git branch -d # Delete remote branch git push origin --delete old-feature
9. File History Detective (Log File)
The Problem: Who changed this file and why is it broken?
The Solution: git log -- <file>
# See file history git log -- path/to/file.js # See actual changes git log -p -- path/to/file.js # See summary of changes git log --stat -- path/to/file.js
It’s like having a time machine for your code!
Detective tools:
# See who changed what git blame file.js # Find when line was added git log -L 10,20:file.js # See file at specific commit git show commit-hash:path/to/file.js
10. The Blame Game (Git Blame)
The Problem: There’s a bug, and you need to know who to ask about it.
The Solution: git blame <filename>
# See who changed each line git blame file.js # Ignore whitespace changes git blame -w file.js # Show readable dates git blame --date=relative file.js
It’s not about pointing fingers – it’s about finding the right person to help!
Advanced blame:
# Ignore moved lines git blame -M file.js # See specific lines git blame -L 10,20 file.js # See who moved/copied code git blame -CCC file.js
11. Bug Detective (Git Bisect)
The Problem: Something’s broken, but you have no idea when it broke. Checking every commit would take forever!
The Solution: git bisect
– your time-traveling bug detective
# Start the investigation git bisect start # Mark current state as broken git bisect bad # Mark last known good commit git bisect good abc123
Think of it like a binary search for bugs – Git becomes your detective partner, helping narrow down exactly when things went wrong!
Real-world example:
# Start the hunt git bisect start git bisect bad # Current version is broken git bisect good v2.0 # Version 2.0 worked fine # Git checks out middle commit # Test your application git bisect good # If this commit works git bisect bad # If this commit is broken # When found, reset to normal git bisect reset
Pro tip: You can even automate the process!
# Automatic binary search with a test script git bisect start HEAD v2.0 git bisect run npm test
12. Emergency Exit (Merge Abort)
The Problem: You started a merge and… oh no, it’s a mess of conflicts!
The Solution: git merge --abort
# Escape from merge hell git merge --abort # Check you're back to safety git status
It’s like having an emergency exit button – sometimes the best solution is to start fresh!
When to use it:
- Merge conflicts are too complex
- You merged the wrong branch
- You need to rethink your strategy
# Safe merge workflow git checkout main git merge feature-branch # If things go wrong... git merge --abort # Take a coffee break, then try again
13. Message Hunter (Grep in Git)
The Problem: You remember making a change, but can’t remember which commit it was in.
The Solution: git log --grep="search term"
# Search commit messages git log --grep="fix login" # Case-insensitive search git log --grep="fix login" -i # Search by author and term git log --grep="fix" --author="Jane"
It’s like having Ctrl+F for your entire Git history!
Advanced searching:
# Search for multiple terms git log --grep="login" --grep="auth" # Search commits affecting specific files git log --grep="fix" -- *.js # Show patches that match git log -p --grep="login"
14. Version Milestone (Git Tags)
The Problem: You need to mark important points in your project’s history.
The Solution: git tag
– your project’s milestone marker
# Create annotated tag git tag -a v1.0 -m "Version 1.0 release" # List all tags git tag -l # Push tags to remote git push origin --tags
Think of it like placing bookmarks in your project’s story!
Tag management:
# Create lightweight tag git tag v1.0-beta # Tag specific commit git tag -a v1.0 abc123 # Delete tag git tag -d v1.0-beta git push origin :v1.0-beta # Delete remote tag
15. Clean Slate (Git Clean)
The Problem: Your working directory is cluttered with untracked files.
The Solution: git clean
– your workspace vacuum cleaner
# See what would be removed git clean -n # Remove untracked files git clean -f # Remove files and directories git clean -fd
⚠️ Warning: This is permanent! Use -n
(dry run) first!
Safety first:
# Interactive cleaning git clean -i # Remove ignored files too git clean -fdx # Remove only ignored files git clean -fdX
16. Time Machine (Git Reflog)
The Problem: “I messed up bad… I need to go back in time!”
The Solution: git reflog
– your Git time machine
# See all Git operations git reflog # Restore to specific point git reset --hard HEAD@{2}
It’s like having infinite undo levels for your repository!
Recovery examples:
# Find lost commit git reflog show # Recover deleted branch git checkout -b recovered-branch HEAD@{1} # Recover after bad reset git reset --hard HEAD@{1}
17. Combine Commits (Squash)
The Problem: Your feature branch has 20 commits of “WIP” and “fix typo”
The Solution: Interactive rebase with squash
# Squash last 3 commits git rebase -i HEAD~3 # In the editor: pick abc123 Add login feature squash def456 Fix typo squash ghi789 Fix tests
Think of it like compressing multiple drafts into one clean final version!
Pro squashing:
# Squash all commits on feature branch git rebase -i main # Abort if things go wrong git rebase --abort # Continue after resolving conflicts git rebase --continue
18. Undo Changes (Revert)
The Problem: You need to undo changes, but others have already pulled your commits.
The Solution: git revert
– the safe way to undo
# Create new commit that undoes changes git revert abc123 # Revert multiple commits git revert abc123..def456
Unlike reset, revert is safe for shared branches – it creates a new commit instead of rewriting history!
Advanced revert:
# Revert merge commit git revert -m 1 merge-commit-hash # Revert without committing git revert -n abc123 # Revert a revert (re-apply changes) git revert abc123 # hash of the revert commit
19. Visual History (Branch Graph)
The Problem: You need to understand how all your branches fit together.
The Solution: git log --graph
– your repository’s family tree
# Pretty branch visualization git log --graph --oneline --all --decorate # With more details git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
It’s like having a map of your project’s history!
Customization:
# Save as alias git config --global alias.graph "log --graph --oneline --all" # Filter by date git log --graph --since="1 week ago" # Focus on specific branches git log --graph main feature-branch
20. Command Completion (Auto-complete)
The Problem: Typing full Git commands is slow and error-prone.
The Solution: Git auto-completion – let Tab be your typing assistant!
Setup (Bash):
# For Ubuntu/Debian sudo apt-get install bash-completion # For macOS with Homebrew brew install git bash-completion
Add to your .bashrc
:
if [ -f /usr/share/bash-completion/completions/git ]; then . /usr/share/bash-completion/completions/git fi
Usage examples:
git ch<Tab> # Expands to checkout git co ma<Tab> # Expands to main git pull or<Tab> # Expands to origin
Bonus Tips for All 20 Tricks
1. Safety First
- Always check
git status
before any major operation - Use
--dry-run
or preview options when available - Create backup branches for risky operations
2. Productivity Boosters
- Create aliases for your most-used commands
- Learn one new trick at a time
- Practice in a test repository
3. Workflow Integration
- Document your favorite commands
- Share knowledge with your team
- Create team conventions for complex operations
Remember: These aren’t just tricks – they’re tools that make you a more efficient developer. Start with the ones that solve your immediate pain points, and gradually expand your Git toolbox!