my-notes

Useful_Git_Snippets

1 min read

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

Bookmark This Page

Reference these snippets when needed.

Practice in Test Repo

Try dangerous commands in a test repo first.



#git #snippets #reference #solutions

Built with mdgarden