Nexus Learn

Git Cheat Sheet

The Git commands you will use every day, in the order you will need them. Git saves snapshots of your project, so you can go back, work in parallel, and share code with a team.

Set up

CommandWhat it does
git config --global user.name "Your Name"Set the name on your commits (once per computer).
git config --global user.email "[email protected]"Set the email on your commits.
git initStart tracking the current folder with Git.
git clone <url>Download a copy of an existing project.

Everyday work

CommandWhat it does
git statusSee what changed and what is ready to commit.
git add <file>Choose a file for the next commit.
git add .Choose all changed files in this folder.
git commit -m "Describe the change"Save a snapshot with a short message.
git diffSee the exact lines you changed but have not added yet.
git log --onelineShow the history, one line per commit.

Branches

CommandWhat it does
git branchList branches. The current one has a star.
git switch -c new-ideaMake a new branch and move to it.
git switch mainMove to an existing branch.
git merge new-ideaBring another branch's work into the one you are on.
git branch -d new-ideaDelete a branch you have already merged.

Working with a remote (GitHub)

CommandWhat it does
git remote -vShow where your project is shared.
git push -u origin mainUpload your commits for the first time and link the branch.
git pushUpload new commits.
git pullDownload new commits and merge them into your branch.
git fetchDownload new commits without merging them yet.

Undoing things

CommandWhat it does
git restore <file>Throw away your changes to a file. This cannot be undone.
git restore --staged <file>Take a file out of the next commit but keep your changes.
git revert <commit>Make a new commit that cancels an older one. Safe for shared work.
git reset --soft HEAD~1Undo the last commit but keep your changes ready to commit.
git stashPut your unfinished work aside. Bring it back with git stash pop.

The basic flow

Change files, then git add, then git commit, then git push. Before you start working, run git pull so you have the latest version.

Frequently asked questions

What is the difference between Git and GitHub?

Git is the tool that tracks your project's history on your computer. GitHub is a website that stores Git projects online so teams can share them.

What is the difference between git fetch and git pull?

git fetch only downloads new commits. git pull downloads them and also merges them into your current branch.

How do I undo my last commit?

If you have not pushed it, use git reset --soft HEAD~1 to undo it and keep your changes. If you have already pushed it, use git revert instead.

Test yourself: practice questions on this topic. More cheat sheets: SQL Cheat Sheet · Python Cheat Sheet · Linux Commands Cheat Sheet · Big-O cheat sheet