Back to blog
·18 min read

The Complete Git Cheatsheet: Essential Commands for Every Developer

A comprehensive reference guide to Git commands covering everything from basic operations to advanced workflows. Includes setup, branching, merging, remote repositories, stashing, and collaboration strategies with practical examples.

GitVersion ControlDevOpsDeveloper ToolsWorkflow

Git is the backbone of modern software development, yet many developers only scratch the surface of its capabilities. Whether you're committing your first change or managing complex collaborative workflows, having a solid Git reference can save hours of frustration.

This comprehensive cheatsheet covers everything from basic commands to advanced operations, organized by use case so you can quickly find what you need.

Setup and Configuration

Before diving into Git commands, let's configure your environment properly.

Initial Setup

Start a new repository:

git init

Creates a new Git repository in the current directory. This initializes the .git folder containing all version control metadata.

Clone an existing repository:

git clone https://github.com/username/repository.git

Creates a local copy of a remote repository, including all commit history and branches.

Clone to a specific directory:

git clone https://github.com/username/repository.git my-project

Configuration Essentials

Set your identity globally:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

These settings appear in every commit you make. Use --global for all repositories, or --local for repository-specific settings.

View all configuration:

git config --list

Shows all Git settings, including user info, aliases, and editor preferences.

Set your preferred editor:

git config --global core.editor "code --wait"  # VS Code
git config --global core.editor "vim"          # Vim
git config --global core.editor "nano"         # Nano

This editor opens when Git needs commit messages or interactive operations.

Enable colored output:

git config --global color.ui auto

Makes Git output more readable with color-coded information.

Create command shortcuts (aliases):

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'

Now you can use git co instead of git checkout, git st instead of git status, etc.

Cache credentials temporarily:

git config --global credential.helper 'cache --timeout=3600'

Caches your Git credentials for 1 hour (3600 seconds), avoiding repeated password prompts.

File Operations

Basic File Management

Check repository status:

git status

Shows which files are staged, unstaged, or untracked. This should be your most-used Git command.

Stage files for commit:

git add filename.txt              # Stage specific file
git add folder/                   # Stage entire folder
git add *.js                      # Stage all JS files
git add .                         # Stage all changes

Stage interactively (choose specific changes):

git add -p

Lets you review and stage changes chunk by chunk—perfect for committing only related changes.

Remove files:

git rm filename.txt               # Delete and stage removal
git rm --cached filename.txt      # Unstage but keep in working directory
git rm -r folder/                 # Recursively remove directory

Rename or move files:

git mv old-name.txt new-name.txt
git mv file.txt folder/file.txt

Git tracks the rename intelligently instead of treating it as delete + add.

Commit staged changes:

git commit -m "Add user authentication feature"
git commit -m "Fix bug in login flow" -m "Detailed explanation here"

The first -m is the subject line, additional -m flags add body paragraphs.

Amend the last commit:

git commit --amend -m "Updated commit message"
git commit --amend --no-edit      # Keep existing message

Useful for fixing typos or adding forgotten files to the last commit.

Viewing Changes

See unstaged changes:

git diff

Shows what you've changed but haven't staged yet.

See staged changes:

git diff --cached
git diff --staged

Shows what will be included in the next commit.

Compare specific commits:

git diff abc123..def456           # Compare two commits
git diff HEAD~2..HEAD             # Compare 2 commits ago to now
git diff main..feature-branch     # Compare branches

See change statistics:

git diff --stat

Shows files changed and line counts without full diff output.

Ignore file changes temporarily:

git update-index --assume-unchanged config.local.js

Tells Git to treat a tracked file as unchanged. Useful for local configuration files.

Resume tracking changes:

git update-index --no-assume-unchanged config.local.js

Branching and Merging

Branches are Git's killer feature, enabling parallel development without conflicts.

Basic Branch Operations

List all branches:

git branch                        # Local branches
git branch -r                     # Remote branches
git branch -a                     # All branches (local + remote)

Create a new branch:

git branch feature-login

Creates the branch but doesn't switch to it.

Switch to a branch:

git checkout feature-login
git switch feature-login          # Modern alternative

Create and switch in one command:

git checkout -b feature-login
git switch -c feature-login       # Modern alternative

Rename a branch:

git branch -m old-name new-name   # Rename any branch
git branch -m new-name            # Rename current branch

Delete a branch:

git branch -d feature-login       # Safe delete (prevents data loss)
git branch -D feature-login       # Force delete

Advanced Branch Management

View branches with details:

git branch -vv

Shows last commit on each branch plus tracking information.

Create tracking branch:

git checkout -b local-branch origin/remote-branch
git branch --track local-branch origin/remote-branch

Sets up a local branch to track changes from a remote branch.

Set existing branch to track remote:

git branch -u origin/main
git branch --set-upstream-to=origin/main

Merging Branches

Merge a branch into current branch:

git merge feature-login

Combines the specified branch's changes into your current branch.

Merge with commit message:

git merge feature-login -m "Merge login feature"

Abort a merge if conflicts arise:

git merge --abort

Cancels the merge and returns to the pre-merge state.

Fast-forward merge only:

git merge --ff-only feature-login

Only merges if it can be done via fast-forward, preventing merge commits.

Rebasing

Rebase current branch onto another:

git rebase main

Replays your commits on top of the main branch, creating a linear history.

Interactive rebase (edit history):

git rebase -i HEAD~3              # Edit last 3 commits
git rebase -i abc123              # Rebase back to commit abc123

Opens an editor where you can:

  • Reorder commits
  • Squash multiple commits into one
  • Edit commit messages
  • Delete commits

Continue after resolving conflicts:

git rebase --continue

Abort a rebase:

git rebase --abort

Skip a commit during rebase:

git rebase --skip

Remote Repositories

Working with remote repositories is essential for collaboration.

Managing Remotes

List remote repositories:

git remote                        # Show names
git remote -v                     # Show names and URLs

Add a new remote:

git remote add origin https://github.com/username/repo.git
git remote add upstream https://github.com/original/repo.git

Remove a remote:

git remote rm origin

Rename a remote:

git remote rename old-name new-name

Show remote details:

git remote show origin

Displays fetch/push URLs, tracked branches, and local branch configurations.

Fetching and Pulling

Download remote changes (don't merge):

git fetch origin                  # Fetch from origin
git fetch --all                   # Fetch from all remotes
git fetch -p                      # Prune deleted remote branches

Download and merge remote changes:

git pull origin main
git pull                          # Pull from tracked branch
git pull --rebase                 # Rebase instead of merge

Fetch and prune obsolete remote branches:

git fetch -p

Removes local references to remote branches that no longer exist.

Pushing Changes

Push to remote branch:

git push origin main
git push origin feature-login

Push and set tracking relationship:

git push -u origin feature-login

After this, you can use git push without specifying remote/branch.

Force push (dangerous!):

git push --force origin main
git push --force-with-lease origin main  # Safer alternative

--force-with-lease prevents overwriting work if the remote has changes you don't have locally.

Push all branches:

git push --all origin

Push tags:

git push --tags                   # Push all tags
git push origin v1.0.0            # Push specific tag

Delete remote branch:

git push origin --delete feature-login
git push origin :feature-login    # Shorthand syntax

Commit History

Understanding your project's history is crucial for debugging and collaboration.

Viewing Commit History

Show commit history:

git log

Displays full commit history with SHA, author, date, and message.

Condensed one-line format:

git log --oneline

Shows abbreviated commit hash and message only.

Visualize branch structure:

git log --graph --oneline --all

ASCII graph showing branch relationships and merge points.

Filter by author:

git log --author="John Doe"
git log --author="john@example.com"

Filter by date:

git log --since="2025-01-01"
git log --until="2025-06-01"
git log --since="2 weeks ago"
git log --since="3 days ago"

Filter by commit message:

git log --grep="bug fix"
git log --grep="feature" -i         # Case-insensitive

Show file changes in commits:

git log --stat                      # Show files changed
git log -p                          # Show full diff
git log -p filename.txt             # Show changes to specific file

Custom format:

git log --pretty=format:"%h - %an, %ar : %s"
git log --pretty=format:"%C(yellow)%h%C(reset) %C(blue)%an%C(reset) %s"

Format placeholders:

  • %h - Abbreviated commit hash
  • %an - Author name
  • %ar - Author date, relative
  • %s - Commit subject
  • %C(color) - Color output

Show specific commit:

git show abc123
git show HEAD                       # Show last commit
git show HEAD~2                     # Show 2 commits back

Find who changed each line:

git blame filename.txt
git blame -L 10,20 filename.txt     # Only lines 10-20

Commit Management

Undo last commit (keep changes):

git reset --soft HEAD~1

Undo last commit (discard changes):

git reset --hard HEAD~1

Undo commit by creating inverse commit:

git revert abc123

Creates a new commit that undoes the changes from commit abc123. Safer than reset for public branches.

View reflog (command history):

git reflog

Shows every change to HEAD, including deleted commits. Lifesaver for recovering "lost" work.

Recover deleted commit:

git reflog                          # Find commit hash
git checkout -b recovery-branch abc123

Tags

Tags mark important points in history, like releases.

List all tags:

git tag
git tag -l "v1.*"                   # Filter tags matching pattern

Create lightweight tag:

git tag v1.0.0

Create annotated tag (recommended):

git tag -a v1.0.0 -m "Release version 1.0.0"

Annotated tags store author, date, and message.

Tag a specific commit:

git tag v0.9.0 abc123

Show tag information:

git show v1.0.0

Delete local tag:

git tag -d v1.0.0

Delete remote tag:

git push origin --delete v1.0.0
git push origin :refs/tags/v1.0.0  # Alternative syntax

Push tags to remote:

git push origin v1.0.0              # Push specific tag
git push origin --tags              # Push all tags

Stashing

Stashing temporarily saves uncommitted changes, perfect for switching contexts quickly.

Save current changes:

git stash
git stash save "Work in progress on login feature"

Include untracked files:

git stash save -u "Include new files"

List all stashes:

git stash list

Output example:

stash@{0}: WIP on feature-login: abc123 Add validation
stash@{1}: On main: def456 Experiment with API

Apply most recent stash:

git stash apply                     # Keep stash in list
git stash pop                       # Apply and remove from list

Apply specific stash:

git stash apply stash@{1}
git stash pop stash@{1}

View stash contents:

git stash show                      # Summary
git stash show -p                   # Full diff
git stash show stash@{1}            # Specific stash

Delete specific stash:

git stash drop stash@{1}

Delete all stashes:

git stash clear

Create branch from stash:

git stash branch new-feature stash@{0}

Creates a branch and applies the stash to it.

Cherry-Picking and Patches

Sometimes you need to apply specific commits without a full merge.

Cherry-Picking

Apply specific commit to current branch:

git cherry-pick abc123

Cherry-pick multiple commits:

git cherry-pick abc123 def456 ghi789

Cherry-pick a range of commits:

git cherry-pick abc123..def456

Cherry-pick without committing:

git cherry-pick -n abc123
git cherry-pick --no-commit abc123

Stages the changes but doesn't commit, letting you modify before committing.

Abort cherry-pick:

git cherry-pick --abort

Continue after resolving conflicts:

git cherry-pick --continue

Creating and Applying Patches

Generate patch file:

git format-patch abc123             # Patch for commits after abc123
git format-patch -1 abc123          # Patch for single commit
git format-patch HEAD~3             # Last 3 commits

Apply patch:

git apply patch-file.patch          # Apply but don't commit
git am patch-file.patch             # Apply and commit

Check if patch applies cleanly:

git apply --check patch-file.patch

Advanced Operations

Submodules

Submodules let you include other Git repositories within your project.

Add submodule:

git submodule add https://github.com/user/library.git libs/library

Initialize submodules after cloning:

git submodule update --init --recursive

Update submodules to latest:

git submodule update --remote

Run command in all submodules:

git submodule foreach 'git pull origin main'

Bisecting (Binary Search for Bugs)

Find which commit introduced a bug using binary search.

Start bisecting:

git bisect start

Mark current state as bad:

git bisect bad

Mark a known good commit:

git bisect good abc123

Git automatically checks out the midpoint commit. Test your code, then:

git bisect good    # If this commit works
git bisect bad     # If this commit has the bug

Repeat until Git identifies the problematic commit.

End bisecting session:

git bisect reset

Automate with a test script:

git bisect start
git bisect bad HEAD
git bisect good v1.0.0
git bisect run npm test

Git runs the test at each commit and automatically finds the bad commit.

Repository Maintenance

Verify repository integrity:

git fsck

Checks for corrupted objects.

Optimize repository:

git gc

Garbage collects unreachable objects and optimizes storage.

Aggressive optimization:

git gc --aggressive --prune=now

Remove untracked files:

git clean -n                        # Dry run (preview)
git clean -f                        # Remove files
git clean -fd                       # Remove files and directories
git clean -fdx                      # Remove files, directories, and ignored files

Search for text in tracked files:

git grep "function"                 # Search all files
git grep "TODO" -- "*.js"           # Search only JS files
git grep -n "error"                 # Show line numbers

Collaboration Workflows

Pull Requests and Code Review

Generate pull request summary:

git request-pull v1.0 https://github.com/user/repo.git feature-branch

Creates a summary of changes suitable for pull request descriptions.

Show author contributions:

git shortlog
git shortlog -sn                    # Summary with commit counts
git shortlog --since="6 months ago"

List tracked files:

git ls-files
git ls-files --others               # Untracked files
git ls-files --ignored              # Ignored files

Useful Workflow Commands

Stash, pull, pop (safe update):

git stash
git pull
git stash pop

Undo local changes to specific file:

git checkout -- filename.txt
git restore filename.txt            # Modern alternative

Unstage file:

git reset HEAD filename.txt
git restore --staged filename.txt   # Modern alternative

Discard all local changes:

git reset --hard HEAD

View file from another branch:

git show feature-branch:path/to/file.txt

Find commits that add/remove text:

git log -S "function_name"

Useful for finding when a function was added or removed.

Common Workflows and Best Practices

Feature Branch Workflow

  1. . Create feature branch:
git checkout -b feature-user-auth

2. Make changes and commit:

git add .
git commit -m "Add user authentication"

3. Push to remote:

git push -u origin feature-user-auth

4. Create pull request on GitHub/GitLab

5. After review, merge and cleanup:

git checkout main
git pull
git branch -d feature-user-auth
git push origin --delete feature-user-auth

Fixing Mistakes

Undo last commit but keep changes:

git reset --soft HEAD~1

Change last commit message:

git commit --amend -m "Corrected message"

Forgot to add file to last commit:

git add forgotten-file.txt
git commit --amend --no-edit

Accidentally committed to wrong branch:

git reset --soft HEAD~1
git stash
git checkout correct-branch
git stash pop
git add .
git commit -m "Message"

Clean Commit History

Squash last 3 commits:

git rebase -i HEAD~3

In the editor, change pick to squash for commits you want to combine.

Remove sensitive data from history:

git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
git push --force

Better alternative (modern):

git filter-repo --path passwords.txt --invert-paths

(Requires git-filter-repo tool)

Git Configuration Tips

Useful Global Settings

Automatically rebase on pull: git config --global pull.rebase true

Use shorter status output: git config --global status.short true

Always show diff when committing: git config --global commit.verbose true

Auto-correct typos: git config --global help.autocorrect 1

Set default branch name: git config --global init.defaultBranch main

Better diff algorithm: git config --global diff.algorithm histogram

Useful Aliases

Add these to ~/.gitconfig:

[alias]
    # Short status
    s = status -s
    # Pretty log
    l = log --graph --pretty=format:'%C(yellow)%h%C(reset) -%C(red)%d%C(reset) %s %C(green)(%cr) %C(bold blue)<%an>%C(reset)' --abbrev-commit
    # Show last commit
    last = log -1 HEAD
    # Unstage file
    unstage = reset HEAD --
    # Show changes to be committed
    staged = diff --cached
    # Amend without editing message
    amend = commit --amend --no-edit
    # Checkout
    co = checkout
    # Branch
    br = branch
    # Commit
    ci = commit
    # List aliases
    aliases = config --get-regexp alias

Quick Reference Summary

Most-Used Commands

Daily workflow

git status
git add .
git commit -m "Message"
git push

Branch management

git checkout -b new-branch
git merge feature-branch
git branch -d old-branch

Syncing

git fetch
git pull
git push

Viewing history

git log --oneline
git diff

Undoing changes

git reset --soft HEAD~1
git checkout -- file.txt
git revert abc123

When Things Go Wrong

Lost work?

git reflog

Merge conflicts?

git merge --abort
git status

Fix conflicts, then:

git add .
git commit

Accidentally committed?

git reset --soft HEAD~1

Need to start over?

git reset --hard HEAD

Remote rejected push?

git pull --rebase
git push

Key Takeaways

  1. . Commit often: Small, focused commits are easier to review and revert

2. Use branches: Never work directly on main/master in collaborative projects

3. Write clear messages: Future you will thank present you

4. Pull before push: Always sync with remote before pushing changes

5. Learn rebasing: Keeps history clean and linear

6. Use stash: Switch contexts without committing half-done work

7. Explore reflog: Your safety net for "deleted" commits

8. Set up aliases: Save time on frequently-used commands

9. Read the docs: git help <command> is your friend

10. Practice in test repos: Experiment fearlessly before trying advanced operations on production code

Git mastery takes time, but having this reference at your fingertips accelerates the learning process. Bookmark this page and return whenever you need a quick reminder. The more you use these commands, the more they'll become second nature.

Happy versioning!