The Forever Git Cheat Sheet

How-To Reference

Git is great at throwing wrenches in the work. For reference here is everything I’ve learned how to fix.

Table Of Contents

Helpful Git Resources

I want to match HEAD back to the origin

Answer on Stack Overflow

git fetch origin
git reset --hard origin/branch-name

I want to drop all unstaged edits and go back to my last commit

Answer on Stack Overflow

git checkout .

I want to go back to my last commit but keep all file edits

Answer on Stack Overflow

git reset HEAD^

Delete Remote & Local Branch

Answer on Stack Overflow

# DELETE REMOTE BRANCH
git push origin -d branch-name

# DELETE LOCAL BRANCH
git branch -d branch-name

Remove File/Dir From Remote & Keep It Locally

Answer on Stack Overflow

git rm -r --cached some-file-or-directory
git commit -m 'Remove the now ignored file/directory'
git push origin master

Update Local Repo To See All New Remote Branches

Stack Overflow answer

git remote update origin --prune

Rename directories in GitHub (i.e. fix casing mismatch)

StackOverflow answer

This is a manual process if the directories are already cased properly locally. The problem is that by default git ignores case changes for filenames and directory names. Here is an answer explaining how to change that (though not recommended, read comments), and here’s a potential fix if the files/folders are not cased properly locally.

Check out a Pull Request on the original repo when I have a fork on my local machine

The GitHub PR page includes instructions for checking out a PR on the command line, but if you are running a fork locally, you need to work with the upstream branch instead of the origin branch.

First make sure the original repo has been added as an upstream source

git fetch upstream
git checkout -b branch-name upstream/branch-name

Keep Forked Repo Up To Date With Original Repo

StackOverflow answer

First make sure the original repo has been added as an upstream source

git checkout master
git fetch upstream
git merge upstream/master

Amend The Commit Message Of The Most Recent Local Commit

Note: don’t do this for commits that have already been pushed to a remote repo, especially in a collaborative repo!

git commit --amend -m "new commit message"

To edit the commit body in addition to the message subject, omit the -m flag.

Rename Master Branch To Main

$ git branch -m master main
$ git push origin HEAD
# Change default branch on GitHub if repo is on GitHub
$ git branch -D master
$ git push origin :master
# Update any CD/CI.