Getting unstuck from Git

At some point something will go wrong with Git

Here are a few helpful ways to get unstuck

Do NOT run these on your current project

You've all been writing some great code this week and I don't want you to lose any of it while practicing Git.

I made a typo in my last commit message

git commit --amend

I forgot to add something to my last commit

# make your change
git add . 
# or add individual files
git commit --amend
# follow prompts to change or keep the commit message

I committed something late last night and stuff broke

# Find the commit hash
git log 
git revert commit_hash
# Now add a commit message for that revert

I accidentally committed to master. Needs to be on a new branch

# create a new branch from the current state of master
git branch some-new-branch-name
# remove the commit from the master branch
git reset HEAD~ --hard
git checkout some-new-branch-name
# your commit lives in this branch now 

I committed something to the wrong branch!

# Switch over to an 
existing branch
git checkout existing_branch
# Move the commit from 
the master branch
git cherry-pick master
# Go back to master and 
nuke the latest commit
git checkout master
git reset HEAD~ --hard 

I made some changes to a project and they suck and I want them gone

# You will lose any new uncommitted work
git reset --hard 

While exploring new code I accidentally created a bunch of files/folders

# You will lose any new uncommitted work
git clean -f

I have unsaved changes but need to grab some changes on GitHub

# Temporarily remove new, uncommitted changes from your branch
git stash --include-untracked
git pull --rebase origin master
git stash pop
# You *may* have to fix merge conflicts

I want to rebase a bunch of commits

# To rebase the last 4 commits
git rebase -i HEAD~4
# In the text editor that comes up, replace the words "pick" with "squash" next to the commits you want to squash into the commit before it. Save and close the editor, and git will combine the "squash"'ed commits with the one before it. ​

I royally screwed up the last several commits. I just want life to be good again

# You will lose any new 
uncommitted work
git reflog 
git reset HEAD@{hash}
# You're back in time!

I accidentally committed a really large or private file

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch large_file'  --prune-empty --tag-name-filter cat -- --all

Replace large_file with file/folder you want to remove

Clean up history after removing a file

rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now
# To push these to GitHub (will overwrite past history)
git push --force

Also see: BFG Repo cleaner

When all else fails

# Delete or rename your local copy
git clone <repo>