Git Commands Master Cheat Sheet

A copy-paste-ready guide to essential Git commands for committing, branching, merging, undoing mistakes, and collaborating, organized by task.

7 min read
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

Git Commands Master Cheat Sheet

Why You Need a Git Cheat Sheet

Git is the backbone of modern software development. It tracks every change, lets teams work in parallel, and gives you a safety net when something goes wrong. But Git has a huge command surface, and even experienced developers forget the exact syntax for undoing a commit or cleaning up a branch.

This guide collects the commands you will actually use, grouped by task, with short examples you can paste straight into your terminal. Keep it open in a tab and come back whenever you need a refresher.

Golden rule: when you are unsure, check before you act.

git status              # what is the current state?
git log --oneline -5    # what happened recently?
git help <command>      # full manual for any command

The Mental Model in 30 Seconds

Most Git confusion disappears once you picture the four places your changes can live:

Working Directory  --git add-->  Staging Area  --git commit-->  Local Repo  --git push-->  Remote Repo
   (your files)                   (the index)                   (your history)              (GitHub, GitLab)
  • Working directory: the files you are editing right now.

  • Staging area: a draft of your next commit.

  • Local repository: your saved history on your machine.

  • Remote repository: the shared copy your team pulls from.

1. First-Time Setup

Run these once per machine.

git config --global user.name 'Your Name'
git config --global user.email '[email protected]'
git config --global init.defaultBranch main      # use 'main' for new repos
git config --global core.editor 'code --wait'    # VS Code as the editor
git config --global pull.rebase false            # merge on pull (explicit default)
git config --list                                # review your settings

2. Starting a Repository

git init                                  # turn the current folder into a repo
git clone https://github.com/user/repo.git        # copy a remote repo
git clone [email protected]:user/repo.git            # clone over SSH
git clone --depth 1 <url>                 # shallow clone, latest snapshot only
git clone <url> my-folder                 # clone into a custom folder name

3. The Everyday Loop: Stage and Commit

git status                       # see what changed
git status -s                    # short, compact output
git add file.txt                 # stage one file
git add src/                     # stage a folder
git add .                        # stage everything in the current directory
git add -p                       # stage changes interactively, hunk by hunk
git commit -m 'Add login form'   # commit staged changes
git commit -am 'Fix typo'        # stage tracked files and commit in one step
git commit --amend               # edit the last commit (message or contents)

Pro tip: git add -p is the best habit you can build. It forces you to review every change before it goes into a commit.

Writing good commit messages

  • Use the imperative mood: Add search filter, not Added search filter.

  • Keep the first line under about 50 characters.

  • Explain the why in the body, not just the what.

  • Many teams use prefixes like feat:, fix:, docs:, and refactor: (Conventional Commits).

4. Inspecting Changes and History

git diff                             # unstaged changes
git diff --staged                    # staged changes, ready to commit
git diff main..feature               # compare two branches
git log                              # full history
git log --oneline                    # one line per commit
git log --oneline --graph --decorate --all     # visual branch graph
git log -p file.txt                  # history of a file, with diffs
git log --author='Alice'             # commits by one author
git log --since='2 weeks ago'        # commits from a time range
git log --grep='login'               # search commit messages
git show a1b2c3d                     # details of one commit
git blame file.txt                   # who changed each line, and when

5. Branching

Branches are cheap in Git. Use them freely.

git branch                       # list local branches
git branch -a                    # list local and remote branches
git branch feature-login         # create a branch
git switch feature-login         # move to a branch
git switch -c feature-login      # create and move in one step
git switch -                     # jump back to the previous branch
git branch -m new-name           # rename the current branch
git branch -d feature-login      # delete a merged branch
git branch -D feature-login      # force delete an unmerged branch

git checkout still works for all of this, but git switch and git restore are clearer, and most modern guides recommend them.

6. Merging and Rebasing

Merge

git switch main
git merge feature-login          # merge a branch into main
git merge --no-ff feature-login  # always create a merge commit
git merge --abort                # cancel a merge that went wrong

Rebase

Rebase replays your commits on top of another branch to keep history linear.

git switch feature-login
git rebase main                  # replay your commits on top of main
git rebase -i HEAD~3             # interactively edit the last 3 commits
git rebase --continue            # continue after fixing a conflict
git rebase --abort               # cancel the rebase

With interactive rebase you can squash several commits into one, reword a message, drop a commit, or reorder them.

Rule of thumb: merge to combine shared work, rebase to tidy your own local work. Never rebase commits that other people have already pulled.

Resolving conflicts

When Git cannot merge automatically, it marks the file like this:

<<<<<<< HEAD
your version of the line
=======
the other branch's version
>>>>>>> feature-login

Edit the file to keep what you want, remove the markers, then finish up:

git add file.txt
git commit                       # for a merge
git rebase --continue            # for a rebase

7. Working with Remotes

git remote -v                            # list remotes
git remote add origin <url>              # connect a remote
git fetch                                # download changes, do not merge
git fetch --prune                        # also remove deleted remote branches
git pull                                 # fetch and merge
git pull --rebase                        # fetch and rebase instead of merging
git push                                 # upload commits
git push -u origin feature-login         # push and set the upstream branch
git push --force-with-lease              # safer force push
git push origin --delete feature-login   # delete a remote branch

Never use plain git push --force on a shared branch. --force-with-lease refuses to overwrite work you have not seen.

8. Undoing Things

This is the section people open a cheat sheet for. The right command depends on how far the change has traveled.

Discard or unstage changes

git restore file.txt                 # discard unstaged changes in a file
git restore --staged file.txt        # unstage a file, keep the changes
git restore .                        # discard all unstaged changes

Undo commits locally

git reset --soft HEAD~1      # undo last commit, keep changes staged
git reset HEAD~1             # undo last commit, keep changes unstaged
git reset --hard HEAD~1      # undo last commit AND delete the changes
git commit --amend           # fix the last commit instead

Undo commits that are already pushed

git revert a1b2c3d           # create a new commit that reverses a1b2c3d
git revert HEAD              # reverse the most recent commit

revert is the safe choice for shared branches because it adds history instead of rewriting it.

Remove untracked files

git clean -n                 # dry run: show what would be deleted
git clean -fd                # delete untracked files and folders

Warning: git reset --hard and git clean -fd permanently delete uncommitted work. Run git status and git clean -n first.

9. Stashing: Save Work for Later

Stash is perfect when you need to switch tasks but are not ready to commit.

git stash                        # stash tracked changes
git stash push -m 'wip: search'  # stash with a descriptive name
git stash -u                     # include untracked files
git stash list                   # see all stashes
git stash pop                    # apply the latest stash and remove it
git stash apply stash@{1}        # apply a specific stash, keep it
git stash drop stash@{0}         # delete a stash

10. Tags and Releases

git tag                          # list tags
git tag v1.0.0                   # lightweight tag
git tag -a v1.0.0 -m 'Release 1.0.0'   # annotated tag (recommended)
git push origin v1.0.0           # push one tag
git push --tags                  # push all tags
git tag -d v1.0.0                # delete a local tag

11. Power Moves

Cherry-pick: copy one commit to another branch

git switch main
git cherry-pick a1b2c3d

Bisect: find the commit that introduced a bug

git bisect start
git bisect bad                   # the current commit is broken
git bisect good v1.0.0           # this older commit worked
# Git checks out commits for you to test. After each one, run:
git bisect good                  # or: git bisect bad
git bisect reset                 # finish and return to your branch

Reflog: your safety net

The reflog records every place HEAD has been, even after a bad reset or a deleted branch.

git reflog                       # find the commit you lost
git reset --hard HEAD@{2}        # jump back to that state
git switch -c rescued a1b2c3d    # or recover it as a new branch

If you think you lost commits, the reflog usually still has them for a few weeks.

12. Ignoring Files with .gitignore

Create a .gitignore file in the repo root:

# dependencies
node_modules/

# build output
dist/
*.log

# secrets and local config
.env
.DS_Store

If a file is already tracked, stop tracking it without deleting it from disk:

git rm --cached secrets.env

13. Aliases That Save Keystrokes

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.lg 'log --oneline --graph --decorate --all'
git config --global alias.unstage 'restore --staged'

Now git st and git lg do exactly what you would expect.

14. Common Workflows

Start a feature

git switch main
git pull
git switch -c feature-search
# ...edit, add, commit...
git push -u origin feature-search
# open a pull request

Update your branch with the latest main

git fetch
git rebase origin/main           # or: git merge origin/main

Fix the last commit message

git commit --amend -m 'Better message'

Clean up local branches that are already merged

git branch --merged main | grep -v 'main' | xargs git branch -d

15. Quick Troubleshooting

  • Committed to the wrong branch? Run git branch correct-branch, then git reset --hard HEAD~1 on the wrong branch, then git switch correct-branch.

  • Pushed a secret by accident? Rotate the secret immediately. Removing it from history is secondary, because it may already be copied.

  • Detached HEAD? You checked out a commit instead of a branch. Run git switch -c new-branch to keep your work.

  • Rejected push? Your remote has commits you do not. Run git pull --rebase, resolve any conflicts, then push again.

Safety Habits Worth Building

  1. Commit small and often. Small commits are easy to review, revert, and cherry-pick.

  2. Check git status before every destructive command. It takes one second.

  3. Prefer revert over reset on shared branches. Do not rewrite history others depend on.

  4. Use --force-with-lease, never bare --force.

  5. Never commit secrets. Use .gitignore and environment variables, and rotate anything that leaks.

Final Thoughts

You do not need to memorize every command here. Master the daily loop of status, add, commit, pull, and push, learn switch and merge for branching, and keep restore, reset, revert, and reflog handy for when things go sideways. Everything else can live in this cheat sheet.

Pick one command from this list you have never tried, such as git add -p, git stash, or git bisect, and use it on a real project this week. That is how a cheat sheet turns into real skill.

Comments0

Join the discussion by logging into your account.

No comments yet. Start the conversation.

Arpan Singh

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Arpan Singh's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.