If you've ever forgotten a Git command, accidentally committed the wrong file, or stared at a merge conflict wondering what went wrong, welcome to the club. ๐
Git is one of those tools every developer uses, but nobody wants to memorize every command. The good news? You don't have to.
This cheat sheet covers the Git commands you'll actually need while building projects, collaborating with friends, contributing to open source, or managing your code on GitHub.
No complicated explanations. Just commands, practical examples, and a few warnings to save you from unnecessary pain.
First, what exactly are Git and GitHub?
They're related, but they're not the same thing.
Git: A version control system that tracks changes in your code.
GitHub: An online platform where you can host Git repositories and collaborate with other developers.
Think of Git as your project's history tracker and GitHub as a place to store and share that history online.
1. Install and configure Git
Before using Git, make sure it's installed on your machine.
git --versionDisplays your installed Git version.
Set your name and email. These details are recorded in your commits.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"Check your configuration:
git config --listGet help whenever you forget a command:
git help commit
git commit -hThe first opens detailed documentation, while the second displays a shorter help page.
2. Create or download a repository
A repository, or repo, is a project Git tracks, including its history.
Start tracking an existing project:
git initInitializes Git in your current directory.
Clone an existing project:
git clone https://github.com/username/project.gitDownloads a repository and its available history to your machine.
Clone into a custom folder:
git clone https://github.com/username/project.git my-projectCheck the repository status:
git statusThis is one of the most useful Git commands. It shows your current branch, modified files, staged changes, and other important information.
Pro tip: When you're unsure what state your project is in, run git status first.
3. The everyday Git workflow
Most of your daily Git work follows this simple pattern:
<CodeBlock language="mermaid" editable={false}>flowchart TD
A["Edit your code"] --> B["git status"]
B --> C["git add"]
C --> D["git diff --staged"]
D --> E["git commit"]
E --> F["git push"]
F --> G["Changes uploaded"]
</CodeBlock>
Here's what each step means:
Step | Command | Purpose |
|---|---|---|
Check |
| See what changed |
Stage |
| Select changes for the next commit |
Review |
| Inspect selected changes |
Commit |
| Save a snapshot in local history |
Push |
| Upload commits to a remote repository |
Remember: a commit saves your changes locally. A push sends those commits to a remote repository.
Stage your changes
Add one file:
git add app.pyAdd several files:
git add app.py README.mdStage all changes in the current directory:
git add .Interactively choose which parts of a file to stage:
git add -pThe interactive option is useful when one file contains several unrelated changes and you want to commit only some of them.
Commit your changes
Create a commit with a descriptive message:
git commit -m "Add login validation"View the changes selected for your next commit:
git diff --stagedStage and commit changes to already tracked files in one step:
git commit -am "Fix navigation bug"Important: git commit -am does not automatically include newly created, untracked files. Use git add for those first.
Good commit messages describe what changed:
Add password validationFix mobile navigationUpdate project documentation
Avoid messages like stuff, final final, or it works now. Future you deserves better. ๐ญ
4. Check changes before committing
These commands help you understand exactly what you're about to save.
git statusShows the current state of your files.
git diffDisplays changes that haven't been staged.
git diff --stagedDisplays changes that are staged for the next commit.
git diff HEADShows differences between your working tree and the current commit, including staged and unstaged tracked-file changes.
git diff --statShows a summary of changed files and the size of their changes.
git diff -- path/to/fileDisplays unstaged changes in a particular file.
5. View your project history
Git records commits so you can understand how your project evolved.
View commit history:
git logShow a compact history:
git log --onelineShow branches and merges visually:
git log --oneline --graph --decorate --allInspect a particular commit:
git show <commit-id>Replace <commit-id> with an actual commit hash.
See who last changed each line of a file:
git blame app.pyUseful for tracing the history of a particular line, though it doesn't necessarily tell you why the change was made.
6. Work with branches
Branches let you develop features or fix bugs separately from your main line of development.
Imagine you're building a website. Instead of experimenting directly on main, you create a separate branch for the feature.
List local branches:
git branchList local and remote-tracking branches:
git branch -aCreate a new branch:
git branch feature/loginThis creates the branch but doesn't switch to it.
Create a branch and switch to it:
git switch -c feature/loginSwitch to an existing branch:
git switch mainRename the current branch:
git branch -m new-nameDelete a merged local branch:
git branch -d feature/loginForce-delete a local branch:
git branch -D feature/loginBe careful with -D. It can delete a branch even when Git warns that it hasn't been merged.
Merge branches
First, switch to the branch that should receive the changes.
git switch main
git merge feature/loginGit combines the changes from feature/login into main, potentially creating a merge commit.
If conflicts occur, resolve them in the affected files, stage the resolutions, and complete the merge as instructed by Git.
7. Connect Git to GitHub
A remote is a named reference to another repository, often one hosted on GitHub.
List configured remotes:
git remote -vConnect your local repository to GitHub:
git remote add origin https://github.com/username/project.gitReplace the URL with your repository's actual URL.
Change the URL of an existing remote:
git remote set-url origin https://github.com/username/project.gitDownload remote updates without merging them into your current branch:
git fetch originFetch and integrate changes from the remote branch:
git pull origin mainUpload your current branch to GitHub:
git pushThis works when your branch already has an upstream configured.
Push a new branch and configure its upstream:
git push -u origin feature/loginAfter setting the upstream, you can generally use git push and git pull without specifying the remote and branch every time.
Fetch vs. pull vs. push
Command | What it does |
|---|---|
| Downloads remote updates without integrating them into your current branch |
| Fetches updates and integrates them into your current branch |
| Uploads your local commits to a remote repository |
If someone else has updated your project, git fetch is a useful first step when you want to inspect those changes before integrating them.
8. Undo mistakes without panicking
This is where Git becomes especially useful. But some commands can permanently discard work, so choose carefully.
Unstage a file
Accidentally added a file to staging?
git restore --staged app.pyThis removes it from staging but keeps your changes in the file.
Discard unstaged changes in a file
git restore app.pyWarning: This discards unstaged changes to the file. Make sure you don't need them.
Undo a commit but keep your changes
git reset --soft HEAD~1Moves the current branch back one commit and keeps the changes staged.
To undo the commit while keeping changes in your working tree, unstaged:
git reset --mixed HEAD~1--mixed is the default reset mode.
Undo a commit by creating a new reversing commit
git revert <commit-id>This creates a new commit that reverses the selected commit's changes. It's generally safer than rewriting history that other people may already have pulled.
Discard local changes and reset tracked files
git reset --hard HEADDanger: This discards staged and unstaged changes to tracked files. Uncommitted work can be lost.
It does not remove untracked files. Avoid running destructive commands unless you understand what will be discarded.
Remove untracked files
Preview what would be removed:
git clean -nActually remove untracked files:
git clean -fUse these carefully. They can delete files Git isn't tracking, including work you haven't committed.
9. Temporarily save unfinished work with stash
Imagine you're halfway through a feature and need to switch branches to fix an urgent bug. You aren't ready to commit your current changes.
That's what git stash is for.
Save your changes:
git stash push -m "Work in progress"List saved stashes:
git stash listApply the latest stash and keep it saved:
git stash applyApply the latest stash and remove it from the stash list:
git stash popApply a specific stash:
git stash apply stash@{0}Delete a particular stash:
git stash drop stash@{0}Delete all saved stashes:
git stash clearBe cautious with git stash clear, since it removes every stash entry.
By default, stash primarily saves tracked-file changes. To include untracked files, use:
git stash push -u -m "Include new files"10. Fix common Git problems
Problem: Your local branch and remote branch have diverged
You may see a message saying that the branches have diverged and you need to specify how to reconcile them.
First, check your current state:
git status
git fetch originThen choose an integration strategy appropriate for your project.
Merge remote changes:
git pull --no-rebaseRebase your local commits on top of the remote branch:
git pull --rebaseIf you have uncommitted work, commit or stash it first. If a conflict occurs during a rebase, resolve the files, stage the resolutions, and continue with:
git rebase --continueTo cancel an in-progress rebase:
git rebase --abortProblem: You committed to the wrong branch
If you haven't pushed yet, you can often move the commit to the correct branch. The safest exact steps depend on whether the changes are already on the wrong branch and whether that branch has been shared.
Before resetting anything, inspect the recent history:
git log --oneline -5
git statusAvoid blindly resetting or deleting branches when the commit contains work you need to keep.
Problem: Git says there are merge conflicts
Check which files need attention:
git statusOpen each conflicted file and look for markers such as:
<<<<<<< HEAD
Your current changes
=======
Incoming changes
>>>>>>> feature/loginEdit the file so it contains the correct final version, remove the conflict markers, and stage the resolved file:
git add path/to/fileThen finish the merge or rebase according to the operation you're performing.
Problem: You committed a file you shouldn't have
If the commit hasn't been pushed and it's your most recent commit, you can amend it after removing the unwanted file from staging or tracking, depending on the situation.
For example, to stop tracking a file while keeping it on your machine:
git rm --cached .envAdd the file to .gitignore so Git stops picking it up in future changes.
Important: If .env contained passwords, API keys, or tokens and was pushed to a remote repository, removing it from a later commit is not enough. Revoke or rotate the exposed secrets immediately.
11. Use .gitignore to keep unwanted files out
A .gitignore file tells Git which untracked files or directories to ignore.
Create a file named .gitignore in your project root:
# Dependencies
node_modules/
# Environment variables
.env
.env.*
# Build output
dist/
build/
# Python cache
__pycache__/
*.py[cod]
# Logs
*.log
# Editor settings
.vscode/Adjust these patterns for your project. For example, some teams intentionally commit selected .vscode settings or environment templates.
Check whether Git is ignoring a particular path:
git check-ignore -v .envOne important detail: .gitignore doesn't automatically stop tracking files that Git already tracks. If a file is already tracked, you must untrack it separately.
12. More useful commands worth knowing
Command | Purpose |
|---|---|
| Rename or move a tracked file |
| Remove a file and stage its deletion |
| Stop tracking a file but keep it locally |
| Inspect the latest commit |
| Show the five most recent commits |
| Show local branches and upstream information |
| Remove stale remote-tracking branch references |
| List tags |
| Create a lightweight tag |
| Push tags to the remote |
| Apply a commit onto your current branch |
| Replay current branch commits on top of |
| Inspect recent movements of local branch references |
| Display information about a remote |
| Summarize commit counts by author |
Some commands, such as rebase and cherry-pick, can cause conflicts or require history cleanup. Learn how they work before using them on shared branches.
13. A practical workflow for your next project
Here's a simple example of starting a project and publishing your first feature branch.
Step 1: Clone the repository.
git clone https://github.com/username/my-project.git
cd my-projectStep 2: Create a feature branch.
git switch -c feature/profile-pageStep 3: Make your changes, then inspect them.
git status
git diffStep 4: Stage and review your changes.
git add .
git diff --stagedStep 5: Commit the feature.
git commit -m "Add profile page"Step 6: Push the branch.
git push -u origin feature/profile-pageStep 7: Open a pull request on GitHub.
A pull request lets you propose changes, review code, discuss improvements, and merge the feature into the target branch.
This workflow keeps your work separate from main and makes collaboration easier.
14. Quick reference: The commands to memorize first
If you're just getting started, focus on these before trying to learn everything else.
git status
git add .
git commit -m "Your message"
git log --oneline
git switch -c feature/name
git switch main
git merge feature/name
git pull
git push
git stash
git restore --staged file.txt
git diffThese cover most of the basic tasks you'll encounter when building and maintaining projects.
Final thoughts
You don't need to memorize 50 commands to become comfortable with Git. Start with the everyday workflow, understand what staging and commits actually mean, and gradually learn branching, collaboration, and recovery commands as you need them.
And when something goes wrong? Don't immediately reach for git reset --hard. Run git status, inspect your history, and understand what Git is telling you before making things worse. ๐ญ
Bookmark this cheat sheet for the next time you forget a command.
Further reading
Happy coding, and may your merge conflicts be few. ๐