Git Cheat Sheet

Essential Git commands for cloning, branching, committing, pushing, and syncing code.

Git Cheat Sheet
Photo by Yancy Min / Unsplash

Setup & Configuration

git config --global user.name "Your Name"        # Set your username
git config --global user.email "you@example.com" # Set your email
git config --global core.editor "code --wait"    # Set VS Code as the default editor
git config --global init.defaultBranch main      # Default branch to 'main'

Starting a Project

git init                        # Initialize a new repo in the current folder
git clone <repo-url>            # Clone an existing repo

Working with Branches

git branch                      # List branches
git branch <branch-name>        # Create a new branch
git checkout <branch-name>      # Switch to a branch
git checkout -b <branch-name>   # Create and switch to a new branch
git branch -d <branch-name>     # Delete a local branch

Staging & Committing

git status                      # Check modified files
git add <file>                  # Stage a specific file
git add .                        # Stage all changes
git commit -m "Commit message"  # Commit staged files with a message
git commit --amend              # Edit the last commit message

Updating & Syncing

git pull origin main             # Pull the latest changes from main
git fetch origin                 # Fetch latest changes without merging
git merge main                   # Merge main into the current branch
git rebase main                  # Rebase current branch onto main

Pushing Changes

git push origin <branch-name>    # Push local branch to remote
git push -u origin <branch-name> # Push and set the upstream branch

Undoing Changes

git checkout – <file>           # Discard changes in a file
git reset HEAD <file>            # Unstage a file
git reset --soft HEAD~1          # Undo last commit (keep changes staged)
git reset --hard HEAD~1          # Undo last commit (discard changes)
git revert HEAD                  # Create a new commit to undo the last one

Working with Remote

git remote -v                    # List remote repositories
git remote add origin <url>       # Add a remote repository
git remote remove origin          # Remove remote
git push origin --delete <branch> # Delete a remote branch

Stashing Changes

git stash                        # Stash uncommitted changes
git stash list                   # Show stash history
git stash apply                  # Reapply the last stash
git stash drop                   # Remove last stash

Viewing History & Logs

git log                          # Show commit history
git log --oneline --graph --all  # Show a compact commit history
git diff                         # Show unstaged changes
git diff --staged                # Show staged changes

Tagging a Release

git tag v1.0.0                   # Create a tag
git push origin v1.0.0           # Push tag to remote