0% found this document useful (0 votes)
3 views1 page

Git Cheatsheet

This Git cheatsheet provides essential commands and operations for version control and collaboration, suitable for both beginners and experienced developers. It covers repository setup, file tracking, branch management, remote operations, and more, offering quick references for various Git functionalities. The document also includes advanced features such as stashing, tagging, and conflict resolution to enhance project management efficiency.

Uploaded by

carmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Git Cheatsheet

This Git cheatsheet provides essential commands and operations for version control and collaboration, suitable for both beginners and experienced developers. It covers repository setup, file tracking, branch management, remote operations, and more, offering quick references for various Git functionalities. The document also includes advanced features such as stashing, tagging, and conflict resolution to enhance project management efficiency.

Uploaded by

carmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

labex.

io

Git Cheatsheet
Essential commands for version control and collaboration

This cheatsheet provides a quick reference to fundamental Git operations, syntax, and advanced features, ideal for both beginners and
experienced developers for efficient version control and project management.

Repository Setup File Tracking Branch Management


Initialize and clone repositories Stage and commit changes Create and manage branches

History Analysis Remote Operations


View and analyze commit history Push, pull, and sync changes

Repository Setup & Configuration

Initialize Repository: `git init` Local Configuration: `git config --local`

Create a new Git repository in the current directory. Set repository-specific configuration.

# Initialize new repository # Set for current repo only


git init git config [Link] "Project Name"
# Initialize in new directory # Project-specific email
git init project-name git config [Link] "project@[Link]"
# Initialize bare repository (no working directory)
git init --bare Remote Management: `git remote`
# Use custom template directory
git init --template=path Manage connections to remote repositories.

Clone Repository: `git clone` # Add remote


git remote add origin [Link]
Create a local copy of a remote repository. # List all remotes with URLs
git remote -v
# Clone via HTTPS # Show detailed remote info
git clone [Link] git remote show origin
# Clone via SSH # Rename remote
git clone git@[Link]:user/[Link] git remote rename origin upstream
# Clone with custom name # Remove remote
git clone [Link] local-name git remote remove upstream
# Shallow clone (latest commit only)
git clone --depth 1 [Link] Credential Storage: `git config credential`

Store authentication credentials to avoid repeated login.


Global Configuration: `git config`

Set up user information and preferences globally. # Cache for 15 minutes


git config --global [Link] cache
git config --global [Link] "Your Name" # Store permanently
git config --global [Link] "[Link]@[Link]" git config --global [Link] store
git config --global [Link] main # Cache for 1 hour
# View all configuration settings git config --global [Link] 'cache --
git config --list timeout=3600'

Repository Info & Status


Understand the current state and history of your repository.

01 02 03

Check Status: `git status` View Differences: `git diff` View History: `git log`
Display the current state of the working Show changes between different states of Display commit history and repository
directory and staging area. your repository. timeline.

# Full status information # Changes in working directory vs # Full commit history


git status staging git log
# Short status format git diff # Condensed one-line format
git status -s # Changes in staging vs last commit git log --oneline
# Machine-readable format git diff --staged # Show last 5 commits
git status --porcelain # All uncommitted changes git log -5
# Show ignored files too git diff HEAD # Visual branch graph
git status --ignored # Changes in specific file git log --graph --all
git diff [Link]

Staging & Committing Changes

Stage Files: `git add` Unstage Files: `git reset`

Add changes to the staging area for the next commit. Remove files from the staging area or undo commits.

# Stage specific file # Unstage specific file


git add [Link] git reset [Link]
# Stage all changes in current directory # Unstage all files
git add . git reset
# Stage all changes (including deletions) # Undo last commit, keep changes staged
git add -A git reset --soft HEAD~1
# Stage all JavaScript files # Undo last commit, discard changes
git add *.js git reset --hard HEAD~1
# Interactive staging (patch mode)
git add -p Discard Changes: `git checkout` / `git restore`

Revert changes in working directory to last committed state.


Commit Changes: `git commit`

Save staged changes to the repository with a descriptive # Discard changes in file (old syntax)
message. git checkout -- [Link]
# Discard changes in file (new syntax)
# Commit with message git restore [Link]
git commit -m "Add user authentication" # Unstage file (new syntax)
# Stage and commit modified files git restore --staged [Link]
git commit -a -m "Update docs" # Discard all uncommitted changes
# Modify the last commit git checkout .
git commit --amend
# Amend without changing message
git commit --no-edit --amend

Branch Operations

List Branches: `git branch` Merge Branches: `git merge`

View and manage repository branches. Combine changes from different branches.

# List local branches # Merge feature-branch into current branch


git branch git merge feature-branch
# List all branches (local and remote) # Force merge commit
git branch -a git merge --no-ff feature-branch
# List only remote branches # Squash commits before merging
git branch -r git merge --squash feature-branch
# Show last commit on each branch
git branch -v Delete Branches: `git branch -d`

Remove branches that are no longer needed.


Create & Switch: `git checkout` / `git switch`

Create new branches and switch between them. # Delete merged branch
git branch -d feature-branch
# Create and switch to new branch # Force delete unmerged branch
git checkout -b feature-branch git branch -D feature-branch
# Create and switch (new syntax) # Delete remote branch
git switch -c feature-branch git push origin --delete feature-branch
# Switch to existing branch
git checkout main
# Switch to existing branch (new syntax)
git switch main

Remote Repository Operations


Synchronize changes with remote repositories and collaborate with others.

Fetch Updates: `git fetch` Push Changes: `git push`

Download changes from remote repository without merging. Upload local commits to remote repository.

# Fetch from default remote # Push to tracking branch


git fetch git push
# Fetch from specific remote # Push to specific remote branch
git fetch origin git push origin main
# Fetch from all remotes # Push and set upstream tracking
git fetch --all git push -u origin feature
# Fetch specific branch # Force push safely
git fetch origin main git push --force-with-lease

Pull Changes: `git pull` Track Remote Branches: `git branch --track`

Download and merge changes from remote repository. Set up tracking between local and remote branches.

# Pull from tracking branch # Set tracking


git pull git branch --set-upstream-to=origin/main main
# Pull from specific remote branch # Track remote branch
git pull origin main git checkout -b local-branch origin/remote-branch
# Pull with rebase instead of merge
git pull --rebase
# Only fast-forward, no merge commits
git pull --ff-only

Stashing & Temporary Storage


Temporarily save work without committing.

Stash Changes: `git stash` Apply Stashes: `git stash apply`

Temporarily save uncommitted changes for later use. Restore previously stashed changes.

# Stash current changes # Apply latest stash


git stash git stash apply
# Stash with message # Apply specific stash
git stash save "Work in progress on feature X" git stash apply stash@{1}
# Include untracked files # Apply and remove latest stash
git stash -u git stash pop
# Stash only unstaged changes # Delete latest stash
git stash --keep-index git stash drop

List Stashes: `git stash list` Stash Management: Advanced Operations

View all saved stashes. Advanced stash operations for complex workflows.

# Show all stashes # Create branch from stash


git stash list git stash branch new-branch stash@{1}
# Show changes in latest stash # Delete all stashes
git stash show git stash clear
# Show changes in specific stash
git stash show stash@{1}

History & Log Analysis

View Commit History: `git log` Search Repository: `git grep`

Explore repository history with various formatting options. Search for text patterns across repository history.

# Visual branch history # Search for text in tracked files


git log --oneline --graph --all git grep "function"
# Commits by specific author # Search with line numbers
git log --author="John Doe" git grep -n "TODO"
# Recent commits # Search in staged files
git log --since="2 weeks ago" git grep --cached "bug"
# Search commit messages
git log --grep="bug fix" Show Commit Details: `git show`

Display detailed information about specific commits.


Blame & Annotation: `git blame`

See who last modified each line of a file. # Show latest commit details
git show
# Show line-by-line authorship # Show previous commit
git blame [Link] git show HEAD~1
# Blame specific lines # Show specific commit by hash
git blame -L 10,20 [Link] git show abc123
# Alternative to blame # Show commit with file statistics
git annotate [Link] git show --stat

Undoing Changes & History Editing


Correct mistakes and modify repository history safely.

Revert Commits: `git revert` Interactive Rebase: `git rebase -i`

Create new commits that undo previous changes safely. Edit, reorder, or squash commits interactively.

# Revert latest commit # Interactive rebase last 3 commits


git revert HEAD git rebase -i HEAD~3
# Revert specific commit # Rebase current branch onto main
git revert abc123 git rebase -i main
# Revert range of commits # Continue after resolving conflicts
git revert HEAD~3..HEAD git rebase --continue
# Revert without auto-commit # Cancel rebase operation
git revert --no-commit abc123 git rebase --abort

Reset History: `git reset` Cherry-pick: `git cherry-pick`

Move branch pointer and optionally modify working directory. Apply specific commits from other branches.

# Undo commit, keep changes staged # Apply specific commit to current branch
git reset --soft HEAD~1 git cherry-pick abc123
# Undo commit and staging # Apply range of commits
git reset --mixed HEAD~1 git cherry-pick abc123..def456
# Undo commit, staging, and working dir # Cherry-pick without committing
git reset --hard HEAD~1 git cherry-pick -n abc123

Conflict Resolution
Handle and resolve merge conflicts effectively.

Merge Conflicts: Resolution Process Conflict Markers: Understanding the Format

Steps to resolve conflicts during merge operations. Interpret Git's conflict markers in files.

# Check conflicted files <<<<<<< HEAD


git status Current branch content
# Mark conflict as resolved =======
git add [Link] Incoming branch content
# Complete the merge >>>>>>> feature-branch
git commit
# Cancel merge and return to previous state # Edit file to resolve, then:
git merge --abort git add [Link]
git commit
Merge Tools: `git mergetool`
Diff Tools: `git difftool`
Launch external tools to help resolve conflicts visually.
Use external diff tools for better conflict visualization.

# Launch default merge tool


git mergetool # Launch diff tool for changes
# Set default merge tool git difftool
git config --global [Link] vimdiff # Set default diff tool
# Use specific tool for this merge git config --global [Link] vimdiff
git mergetool --tool=meld

Tagging & Releases


Mark important points in repository history.

Create Tags: `git tag` Push Tags: `git push --tags`

Mark specific commits with version labels. Share tags with remote repositories.

# Create lightweight tag # Push specific tag


git tag v1.0 git push origin v1.0
# Create annotated tag # Push all tags
git tag -a v1.0 -m "Version 1.0 release" git push --tags
# Tag specific commit # Push all tags to specific remote
git tag -a v1.0 abc123 git push origin --tags
# Create signed tag
git tag -s v1.0 Delete Tags: `git tag -d`

Remove tags from local and remote repositories.


List & Show Tags: `git tag -l`

View existing tags and their information. # Delete local tag


git tag -d v1.0
# List all tags # Delete remote tag
git tag git push origin --delete tag v1.0
# List tags matching pattern # Alternative delete syntax
git tag -l "v1.*" git push origin :refs/tags/v1.0
# Show tag details
git show v1.0

Git Configuration & Aliases


Customize Git behavior and create shortcuts for efficiency.

View Configuration: `git config --list` Advanced Aliases: Complex Commands

Display current Git configuration settings. Create aliases for complex command combinations.

# Show all config settings git config --global [Link] "log --oneline --graph --all"
git config --list git config --global [Link] "reset HEAD --"
# Show global settings only git config --global [Link] "log -1 HEAD"
git config --global --list git config --global [Link] "!gitk"
# Show repository-specific settings
git config --local --list Editor Configuration: `git config [Link]`
# Show specific setting
Set preferred text editor for commit messages and conflicts.
git config [Link]

Create Aliases: `git config alias` # VS Code


git config --global [Link] "code --wait"
Set up shortcuts for frequently used commands. # Vim
git config --global [Link] "vim"
# git st = git status # Nano
git config --global [Link] status git config --global [Link] "nano"
# git co = git checkout
git config --global [Link] checkout
# git br = git branch
git config --global [Link] branch
# git ci = git commit
git config --global [Link] commit

Performance & Optimization

Repository Maintenance: `git gc` Shallow Clones: Reducing Repository Size

Optimize repository performance and storage. Clone repositories with limited history for faster operations.

# Standard garbage collection # Latest commit only


git gc git clone --depth 1 [Link]
# More thorough optimization # Last 10 commits
git gc --aggressive git clone --depth 10 [Link]
# Run only if needed # Convert shallow to full clone
git gc --auto git fetch --unshallow
# Check repository integrity
git fsck Sparse Checkout: Working with
Subdirectories
Large File Handling: `git lfs`
Check out only specific parts of large repositories.
Manage large binary files efficiently with Git LFS.
git config [Link] true
# Install LFS in repository echo "src/*" > .git/info/sparse-checkout
git lfs install # Apply sparse checkout
# Track PDF files with LFS git read-tree -m -u HEAD
git lfs track "*.pdf"
# List files tracked by LFS
git lfs ls-files
# Migrate existing files
git lfs migrate import --include="*.zip"

Git Installation & Setup


Install and configure Git for your development environment.

Package Managers: `apt`, Download & Install: First-Time Setup: User


`yum`, `brew` Official Installers Configuration
Install Git using system package Use official Git installers for your Configure Git with your identity for
managers. platform. commits.

# Ubuntu/Debian # Download from [Link] git config --global [Link]


sudo apt install git [Link]/downloads "Your Full Name"
# CentOS/RHEL # Verify installation git config --global [Link]
sudo yum install git git --version "[Link]@[Link]"
# macOS with Homebrew # Show Git executable path git config --global
brew install git which git [Link] main
# Windows with winget # Set merge behavior
winget install [Link] git config --global [Link]
false

Git Workflows & Best Practices


Adopt proven workflows for team collaboration and project management.

Feature Branch Workflow Commit Message Conventions

Standard workflow for feature development with isolated Follow conventional commit format for clear project history.
branches.
# Format: <type>(<scope>): <subject>
# Start from main branch git commit -m "feat(auth): add user login functionality"
git checkout main git commit -m "fix(api): resolve null pointer exception"
# Get latest changes git commit -m "docs(readme): update installation
git pull origin main instructions"
# Create feature branch git commit -m "refactor(utils): simplify date formatting"
git checkout -b feature/user-auth
# ... make changes and commits ... Atomic Commits: Best Practices
# Push feature branch
Create focused, single-purpose commits for better history.
git push -u origin feature/user-auth
# ... create pull request ...
# Stage changes interactively
Git Flow: Structured Branching Model git add -p
# Specific change
Systematic approach with dedicated branches for different git commit -m "Add validation to email field"
purposes. # Avoid: git commit -m "Fix stuff" # Too vague
# Good: git commit -m "Fix email validation regex
# Initialize Git Flow pattern"
git flow init
# Start feature
git flow feature start new-feature
# Finish feature
git flow feature finish new-feature
# Start release branch
git flow release start 1.0.0

Troubleshooting & Recovery


Resolve common Git issues and recover from mistakes.

Reflog: Recovery Tool Authentication Issues

Use Git's reference log to recover lost commits. Resolve common authentication and permission problems.

# Show reference log # Use token


git reflog git remote set-url origin
# Show HEAD movements [Link]
git reflog show HEAD # Add SSH key to agent
# Recover lost commit ssh-add ~/.ssh/id_rsa
git checkout abc123 # Windows credential manager
# Create branch from lost commit git config --global [Link] manager-core
git branch recovery-branch abc123
Performance Issues: Debugging
Corrupted Repository: Repair
Identify and resolve repository performance problems.
Fix repository corruption and integrity issues.

# Show repository size


# Check repository integrity git count-objects -vH
git fsck --full # Count total commits
# Aggressive cleanup git log --oneline | wc -l
git gc --aggressive --prune=now # Count branches
# Rebuild index if corrupted git for-each-ref --format='%(refname:short)' | wc -l
rm .git/index; git reset

Reference: This cheatsheet covers essential Git commands and modern practices for efficient version control and collaboration in
software development workflows.

[Link]

You might also like