Useful_Git_Snippets
Useful Git Snippets
Copy-paste solutions for common tasks.
π Undo Operations
Undo Last Commit (Keep Changes)
git reset HEAD~1
Uncommits but keeps file changes.
Undo Last Commit (Discard All)
git reset --hard HEAD~1
β οΈ Permanently discards last commit.
Undo Pushed Commit
git revert HEAD
Creates new commit undoing changes.
Discard All Local Changes
git checkout -- .
Reverts all files to last commit.
Discard Specific File Changes
git checkout -- filename.txt
Reverts specific file.
πΏ Branch Operations
Delete Local Branch
git branch -d branch-name
Deletes if merged.
Force Delete Branch
git branch -D branch-name
Deletes even if unmerged.
Delete Remote Branch
git push origin --delete branch-name
Removes from remote.
Rename Current Branch
git branch -m new-name
Renames local branch.
Delete All Merged Branches
git branch --merged | grep -v "main\|master" | xargs git branch -d
Cleans up merged branches.
π Commit Fixes
Change Last Commit Message
git commit --amend -m "New message"
Updates commit message.
Add File to Last Commit
git add forgotten-file.txt && git commit --amend --no-edit
Adds file without changing message.
Squash Last N Commits
git rebase -i HEAD~3
Opens editor to squash 3 commits.
π Find Things
Find Commit That Introduced Bug
git bisect start && git bisect bad && git bisect good v1.0
Binary search for bug.
Find Who Changed a Line
git blame filename.txt
Shows author of each line.
Search for String in Code
git grep "searchTerm"
Finds in tracked files.
Find Commits by Message
git log --grep="keyword"
Searches commit messages.
Find Deleted File
git log --all --full-history -- "**/filename.*"
Locates when file was deleted.
π§Ή Cleanup
Remove Untracked Files
git clean -fd
Deletes untracked files and directories.
Prune Remote Branches
git fetch --prune
Removes stale remote-tracking branches.
Garbage Collect
git gc --prune=now
Cleans up and optimizes.
π€ Stash Operations
Stash with Message
git stash push -m "Work in progress"
Saves with description.
Apply Specific Stash
git stash apply stash@{2}
Applies stash by index.
Create Branch from Stash
git stash branch new-branch
Makes branch from stash.
π§ Configuration
Show All Config
git config --list --show-origin
Shows config with file sources.
Create Alias
git config --global alias.st status
Now
git st=git status.
Set Pull Rebase
git config --global pull.rebase true
Always rebase on pull.
π‘ Tips
Reference these snippets when needed.
Try dangerous commands in a test repo first.
π Related
#git #snippets #reference #solutions