---
title: "Git"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/git
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Git

Git is a distributed version control system for tracking code changes, collaborating with teams, and managing project history.

8 Categories19 Sections37 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

GitVersion ControlBranchesCommitsCollaborationSCMGitHubGitLab

[Markdown for AI(opens in a new tab)](/git/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Developer Environment & Tooling](/series/developer-environment--tooling)1/6

[NextScreen](/cheatsheets/screen)

All posts in this series (6)

Cheatsheets6

1.  [GitYou are here](/cheatsheets/git)
2.  [Screen](/cheatsheets/screen)
3.  [Tmux](/cheatsheets/tmux)
4.  [Vim](/cheatsheets/vim)
5.  [VS Code](/cheatsheets/vscode)
6.  [Python Virtual Environments Cheatsheet](/cheatsheets/python-venv)

Git is a distributed version control system. Developers use it to track code changes, collaborate with teams, and manage project history. Most software teams build their workflow around it.

## [Key concepts](#key-concepts)

-   **Distributed**: Every developer has a complete copy of the repository history
-   **Branching**: Create isolated lines of development for features and fixes
-   **Commits**: Snapshots of changes with descriptive messages
-   **Merging**: Combine changes from different branches
-   **Tracking**: Monitor changes across files and identify who changed what

## [Common use cases](#common-use-cases)

1.  **Collaborative Development**: Multiple developers working on same project
2.  **Version Control**: Track all changes with full history
3.  **Branching Strategy**: Feature branches, release branches, hotfix branches
4.  **Code Review**: Pull requests and merge reviews before integration
5.  **Rollback Capability**: Revert to previous states if needed

## [Quick reference](#quick-reference)

**Initial Setup**: Configure your identity with `git config --global user.name` and `user.email`

**Start Project**: Use `git init` for new repos or `git clone` to download existing

**Save Work**: `git add` files, then `git commit -m "message"` to create snapshots

**Share Changes**: `git push` to upload, `git pull` to download updates

The sections above cover Git workflows, starting with everyday commands and ending with rebase, bisect, and repository maintenance.

[Getting Started](#category-getting-started)

-   [Git Configuration](#section-git-config)
-   [Initialize and Clone](#section-git-init-clone)

[Basic Commands](#category-basic-commands)

-   [Staging and Committing](#section-add-commit)
-   [Push and Pull](#section-push-pull)
-   [View Status and History](#section-view-history)

[Branches](#category-branches)

-   [Create and Delete Branches](#section-create-delete-branches)
-   [Switch and Merge Branches](#section-switch-branches)
-   [List and Compare Branches](#section-list-branches)

[Logs & History](#category-logs-history)

-   [View Commit History](#section-git-log)
-   [Advanced Log Filtering](#section-log-filtering-revisions)

[Undoing Changes](#category-undoing-changes)

-   [Reset and Revert](#section-reset-revert)
-   [Restore and Checkout Files](#section-restore-checkout)

[Advanced](#category-advanced)

-   [Rebase and Cherry Pick](#section-rebase-cherry-pick)
-   [Stash and Merge](#section-stash-merge)

[Remote Tracking](#category-remote-tracking)

-   [Configure Remotes and Fetch](#section-remotes-fetch)
-   [Tracking Branch Configuration](#section-tracking-branches)

[Extras & Tips](#category-extras-tips)

-   [Bisect and Debugging](#section-bisect-debug)
-   [Signing and Maintenance](#section-signing-cleanup)
-   [Aliases and Shortcuts](#section-aliases-workflows)

No commands found

Try adjusting your search term

## Getting Started

Initialize repositories and configure Git for your first use.

### Git Configuration

Set up your Git identity and configure global preferences.

#### Accessibility

Configuration steps are explained with clear examples

#### Best Practices

-   Set global config once on new machine
-   Use local config for work vs personal projects
-   Configure proper line endings early to avoid whitespace issues

#### Common Errors

-   **Please tell me who you are:** Run git config --global user.name and user.email

#### Keywords

configidentityemailusernamepreferences

[Learn more](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup)

#### Set user identity

Sets the name and email used for commit authorship. Use --global for all repositories or --local for specific project.

Code

Terminal window

```
# Configure user name and emailgit config --global user.name "John Doe"git config --global user.email "john@example.com"
# Configure for specific project onlygit config --local user.name "John Doe"git config --local user.email "john@example.com"
```

Execution

Terminal window

```
git config --global user.name
```

Output

Terminal window

```
John Doe
```

-   Global config is stored in ~/.gitconfig
-   Local config overrides global settings
-   Required before making your first commit

#### Configure editor and defaults

Customize Git behavior with editor preferences, default branch naming, and line ending handling.

Code

Terminal window

```
# Set default editor for commitsgit config --global core.editor "nano"
# Set default branch name for new repositoriesgit config --global init.defaultBranch "main"
# Configure line ending handlinggit config --global core.autocrlf true
```

Execution

Terminal window

```
git config --global --list
```

Output

Terminal window

```
user.name=John Doeuser.email=john@example.comcore.editor=nanoinit.defaultBranch=main
```

-   autocrlf: true (Windows), input (Unix/macOS)
-   View all config with --list flag

### Initialize and Clone

Create new repositories locally or clone existing ones.

#### Accessibility

Clear distinction between creating new and cloning existing repos

#### Best Practices

-   Use SSH for repeated access after key setup
-   Clone with HTTPS if SSH is not configured
-   Use shallow clone for large repos if history not needed

#### Common Errors

-   **Repository not found:** Check URL and repository access permissions

#### Keywords

initclonerepositoryremote

[Learn more](https://git-scm.com/docs/git-clone)

#### Initialize a new repository

Creates a new Git repository in current directory with a hidden .git folder containing repository metadata.

Code

Terminal window

```
# Create new directory and initialize gitmkdir my-projectcd my-projectgit init
# Or initialize git in existing directorycd existing-directorygit init
# Initialize with specific default branchgit init --initial-branch=main
```

Execution

Terminal window

```
git init
```

Output

Terminal window

```
Initialized empty Git repository in /path/to/repo/.git/
```

-   Creates .git directory with Git internals
-   Safe to run multiple times
-   Default branch is master or configurable as main

#### Clone a remote repository

Clones a remote repository to your local machine, including full history and all branches.

Code

Terminal window

```
# Clone with HTTPSgit clone https://github.com/user/repo.git
# Clone with SSHgit clone git@github.com:user/repo.git
# Clone into specific directorygit clone https://github.com/user/repo.git my-folder
# Clone with limited historygit clone --depth 1 https://github.com/user/repo.git
```

Execution

Terminal window

```
git clone https://github.com/user/repo.git
```

Output

Terminal window

```
Cloning into 'repo'...remote: Counting objects: 100%Receiving objects: 100% (150/150), 25.5 KiB | 500 KiB/sResolving deltas: 100% (50/50), done.
```

-   \--depth 1 for shallow clone (faster, less history)
-   Creates directory with repo name by default
-   SSH requires key setup, HTTPS uses credentials

## Basic Commands

Essential commands for daily Git workflow.

### Staging and Committing

Add changes to staging area and create commits.

#### Accessibility

Clear explanation of staging area and commit process

#### Best Practices

-   Write clear, descriptive commit messages
-   Commit logically related changes together
-   Use --amend only on unpushed commits

#### Common Errors

-   **nothing added to commit:** Stage changes first with git add

#### Keywords

addcommitstagingchangessnapshot

[Learn more](https://git-scm.com/docs/git-commit)

#### Stage and commit changes

Adds modified files to staging area and creates a commit with descriptive message.

Code

Terminal window

```
# Check status of repositorygit status
# Stage specific filegit add filename.txt
# Stage all changesgit add .
# Commit staged changesgit commit -m "Add new feature"
# Stage and commit in one commandgit commit -am "Fix bug"
```

Execution

Terminal window

```
git add . && git commit -m "Update code"
```

Output

Terminal window

```
[main a1b2c3d] Update code 3 files changed, 45 insertions(+), 10 deletions(-)
```

-   git add stages changes for commit
-   git commit creates snapshot with message
-   \-m flag for inline commit message
-   \-a flag skips staging for tracked files

#### Amend commits

Modifies the most recent commit by adding changes or changing the message.

Code

Terminal window

```
# Add forgotten file to previous commitgit add forgotten_file.txtgit commit --amend --no-edit
# Change commit messagegit commit --amend -m "Better message"
# Amend without changing messagegit commit --amend --no-edit
# Amend with timestamp updategit commit --amend --date now
```

Execution

Terminal window

```
git commit --amend -m "Updated message"
```

Output

Terminal window

```
[main 5d4e3c2] Updated messageDate: Fri Feb 28 2025 10:30:00 2 files changed, 50 insertions(+)
```

-   Only amend unpushed commits to avoid conflicts
-   \--no-edit keeps original message
-   Useful for fixing small mistakes before pushing

### Push and Pull

Synchronize changes with remote repositories.

#### Accessibility

Clear process flow for syncing with remote

#### Best Practices

-   Pull before pushing to avoid conflicts
-   Use --force-with-lease instead of --force
-   Keep commits organized before pushing

#### Common Errors

-   **Your branch is behind its track:** Run git pull to fetch and merge remote changes

#### Keywords

pushpullremotefetchmerge

[Learn more](https://git-scm.com/docs/git-push)

#### Push changes to remote

Uploads local commits to the remote repository on the specified branch.

Code

Terminal window

```
# Push current branch to remotegit push
# Push to specific remote and branchgit push origin main
# Push all local branchesgit push origin --all
# Push with force (only if needed)git push --force-with-lease
# Push specific taggit push origin v1.0.0
```

Execution

Terminal window

```
git push origin main
```

Output

Terminal window

```
Enumerating objects: 5, done.Writing objects: 100% (3/3), 280 bytesTo github.com:user/repo.git   a1b2c3d..x8y9z0a  main -> main
```

-   Default remote is usually 'origin'
-   First push may require --set-upstream
-   Use --force-with-lease instead of --force

#### Pull changes from remote

Downloads and integrates remote changes into the current branch.

Code

Terminal window

```
# Fetch and merge remote changesgit pull
# Pull from specific remote and branchgit pull origin main
# Pull with rebase instead of mergegit pull --rebase
# Fetch only (don't merge)git fetch
# Fetch from all remotesgit fetch --all
```

Execution

Terminal window

```
git pull origin main
```

Output

Terminal window

```
From github.com:user/repo * branch            main       -> FETCH_HEADFast-forward file.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
```

-   git pull = git fetch + git merge
-   Use --rebase for linear history
-   Always pull before pushing to avoid conflicts

### View Status and History

Check repository status and view change history.

#### Accessibility

Explain what each status and diff output means

#### Best Practices

-   Use git status before committing
-   Review diffs before staging
-   Use git show for viewing specific commits

#### Common Errors

-   **No changes added:** Use git diff to see unstaged changes

#### Keywords

statusdiffshowhistory

[Learn more](https://git-scm.com/docs/git-diff)

#### Check repository status

Shows which files are modified, staged, or untracked in current working directory.

Code

Terminal window

```
# View current statusgit status
# Short status formatgit status -s
# Include untracked filesgit status --include-untracked
```

Execution

Terminal window

```
git status -s
```

Output

Terminal window

```
M config.jsA  new-file.txt?? untracked.txt
```

-   M = modified, A = added, ?? = untracked
-   First letter = staging area, second = working directory

#### View differences in files

Shows line-by-line differences between working directory and staging area or between commits.

Code

Terminal window

```
# View unstaged changesgit diff
# View staged changesgit diff --staged
# View changes in specific filegit diff filename.txt
# View changes between commitsgit diff HEAD~2 HEAD
```

Execution

Terminal window

```
git diff --staged
```

Output

Terminal window

```
diff --git a/file.txt b/file.txtindex 1234567..abcdefg 100644--- a/file.txt+++ b/file.txt@@ -5,7 +5,7 @@ old content-removed line+added line
```

-   Plus sign (+) for added lines
-   Minus sign (-) for removed lines
-   Use --color-words for word-level diff

## Branches

Create, manage, and work with branches for parallel development.

### Create and Delete Branches

Create new branches and delete obsolete ones.

#### Accessibility

Explain branch naming and deletion safety

#### Best Practices

-   Use -d for safe deletion
-   Merge before deleting branches
-   Keep branch names descriptive and consistent

#### Common Errors

-   **Branch is not fully merged:** Use git branch -D to force delete, or merge first

#### Keywords

branchcreatedeletetrackupstream

[Learn more](https://git-scm.com/docs/git-branch)

#### Create and switch branches

Creates a new branch either from current HEAD or specific commit and optionally switches to it.

Code

Terminal window

```
# Create new branchgit branch feature-new
# Create and switch in one commandgit checkout -b feature-new
# Create branch from specific commitgit branch feature-new a1b2c3d
# Create tracking branchgit branch --track feature origin/feature
# Create branch with no upstreamgit branch --no-track feature-local
```

Execution

Terminal window

```
git checkout -b feature-new
```

Output

Terminal window

```
Switched to a new branch 'feature-new'
```

-   Branch name should use hyphens, not spaces
-   New branch contains all commits up to creation point
-   Use descriptive names (feature/\*, fix/\*, etc)

#### Delete branches

Removes branches locally or from remote repository. -d is safe, -D forces deletion.

Code

Terminal window

```
# Delete local branch (safe)git branch -d feature-new
# Force delete unmerged branchgit branch -D feature-new
# Delete remote branchgit push origin --delete feature-new
# Delete multiple branchesgit branch -d feature-1 feature-2 feature-3
```

Execution

Terminal window

```
git branch -d feature-new
```

Output

Terminal window

```
Deleted branch feature-new (was a1b2c3d).
```

-   \-d prevents deleting unmerged branches
-   \-D forces deletion regardless of merge status
-   Deleting remote branch pushes deletion to origin

### Switch and Merge Branches

Switch between branches and merge changes.

#### Accessibility

Clear explanation of merge vs rebase

#### Best Practices

-   Switch to target branch before merging
-   Use --no-ff to preserve branch history
-   Test before merging to main

#### Common Errors

-   **CONFLICT - merge conflict:** Resolve conflicts in editor, then git add and commit

#### Keywords

switchcheckoutmergerebase

[Learn more](https://git-scm.com/docs/git-merge)

#### Switch between branches

Changes working directory to selected branch. Can create new branch at same time.

Code

Terminal window

```
# Switch to existing branchgit checkout main
# Create and switch in one commandgit checkout -b feature
# Switch using new syntaxgit switch main
# Create and switch with new syntaxgit switch -c feature
# Return to previous branchgit checkout -
```

Execution

Terminal window

```
git switch main
```

Output

Terminal window

```
Switched to branch 'main'
```

-   git switch is newer, alias for checkout
-   Save uncommitted changes before switching
-   Use - to switch to previously checked out branch

#### Merge branches

Integrates commits from another branch into the current branch. Fast-forward if possible.

Code

Terminal window

```
# Merge feature branch into current branchgit merge feature
# Merge with no fast-forwardgit merge --no-ff feature
# Squash commits before merginggit merge --squash feature
# Abort merge if conflictsgit merge --abort
```

Execution

Terminal window

```
git merge feature
```

Output

Terminal window

```
Merge made by the 'recursive' strategy. file.txt | 5 +++-- 1 file changed, 2 insertions(+), 3 deletions(-)
```

-   Merge creates merge commit if no fast-forward possible
-   \--no-ff always creates merge commit
-   \--squash combines all commits into single commit

### List and Compare Branches

View and compare branches in repository.

#### Accessibility

Explain branch listing and comparison output

#### Best Practices

-   Delete merged branches regularly
-   Keep active development on feature branches
-   Use --merged to find branches to delete

#### Common Errors

-   **No such branch:** Use git branch -a to list all available branches

#### Keywords

listcomparetrackingremoteupstream

[Learn more](https://git-scm.com/docs/git-branch)

#### List branches

Lists all branches with option to show last commit for each branch.

Code

Terminal window

```
# List local branchesgit branch
# List with last commit infogit branch -v
# List remote branchesgit branch -r
# List all branches (local and remote)git branch -a
# List merged branchesgit branch --merged
# List unmerged branchesgit branch --no-merged
```

Execution

Terminal window

```
git branch -v
```

Output

Terminal window

```
* main       a1b2c3d Update README  feature    x8y9z0a Add new feature  bugfix     p5q6r7s Fix critical bug
```

-   Asterisk (\*) marks current branch
-   \-r shows remote branches
-   \-a shows both local and remote

## Logs & History

View, search, and analyze commit history.

### View Commit History

Display commit history with various formats and filters.

#### Accessibility

Explain log output format and key fields

#### Best Practices

-   Use meaningful commit messages for better log readability
-   Filter logs by author or date for debugging
-   Use --graph for visualizing complex histories

#### Common Errors

-   **No commits yet:** Make first commit before viewing history

#### Keywords

loghistorycommitsgraphformat

[Learn more](https://git-scm.com/docs/git-log)

#### View commit history

Shows commit history in selected format. Use --oneline for concise view, --graph for branch visualization.

Code

Terminal window

```
# View commit historygit log
# View in one-line formatgit log --oneline
# View with branch graphgit log --graph --all --oneline --decorate
# View recent commitsgit log -n 5
# View with statisticsgit log --stat
```

Execution

Terminal window

```
git log --oneline -n 5
```

Output

Terminal window

```
a1b2c3d Update documentationx8y9z0a Add authenticationp5q6r7s Fix login bugm3n4o5p Refactor databasei1j2k3l Initial commit
```

-   Without arguments shows full commit info
-   \--stat shows file changes per commit
-   \--graph helps visualize branching

#### Filter and format logs

Filters log by author, date range, or custom format for precise history searching.

Code

Terminal window

```
# View commits by authorgit log --author="John Doe"
# View commits since dategit log --since="2025-01-01"
# View commits until dategit log --until="2025-02-01"
# Custom formatgit log --pretty=format:"%h %s by %an"
# View specific file historygit log -- filename.txt
```

Execution

Terminal window

```
git log --author="John" --oneline --graph
```

Output

Terminal window

```
* a1b2c3d Update code* x8y9z0a Fix bug* p5q6r7s Add feature
```

-   Useful for tracking specific changes
-   Custom format strings available in docs
-   Filter by file to track changes in specific files

### Advanced Log Filtering

Use revisions and ranges to explore commit history.

#### Accessibility

Clear explanation of revision syntax

#### Best Practices

-   Use HEAD references for recent commits
-   Use ranges to compare branches before merging
-   Combine with --oneline for cleaner output

#### Common Errors

-   **bad revision:** Check revision syntax and available commits

#### Keywords

revisionrangeHEADbranchestags

[Learn more](https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection)

#### Reference commits with revisions

Shows specific commits using HEAD references and relative positioning.

Code

Terminal window

```
# HEAD referencesgit show HEAD           # Most recent commitgit show HEAD~1         # One commit before HEADgit show HEAD~2         # Two commits before HEADgit show HEAD^          # Parent of HEADgit show HEAD^^         # Grandparent of HEAD
# Show specific commitgit show a1b2c3d
# Show commit from taggit show v1.0.0
```

Execution

Terminal window

```
git show HEAD~1
```

Output

Terminal window

```
commit a1b2c3d3f4g5h6i7j8k9l0m1nAuthor: John Doe <john@example.com>Date: Fri Feb 27 2025
Previous commit message
```

-   HEAD~n counts back n commits in history
-   HEAD^ refers to parent commit
-   Use with show, log, diff for detailed exploration

#### Use commit ranges

Shows commits within specified ranges, useful for comparing branches.

Code

Terminal window

```
# Commits in feature but not main (two-dot)git log main..feature
# Commits in either branch (three-dot)git log main...feature
# Commits reachable from branchgit log feature
# Commits in rangegit log a1b2c3d..x8y9z0a
```

Execution

Terminal window

```
git log main..feature --oneline
```

Output

Terminal window

```
p5q6r7s Add feature implementationm3n4o5p Update tests
```

-   Two-dot: commits in first branch only
-   Three-dot: commits in either branch, not both

## Undoing Changes

Revert, reset, and restore changes in various scenarios.

### Reset and Revert

Move HEAD and undo commits permanently or safely.

#### Accessibility

Clear distinction between destructive and safe operations

#### Best Practices

-   Use revert for shared branches
-   Use reset only on local commits
-   Never --hard reset unless certain

#### Common Errors

-   **Cannot revert without resolving conflicts:** Resolve conflicts manually, then complete revert

#### Keywords

resetrevertundoHEADcommits

[Learn more](https://git-scm.com/docs/git-reset)

#### Reset changes

Moves HEAD to previous state. --soft keeps changes staged, --mixed unstages, --hard discards all.

Code

Terminal window

```
# Undo last commit, keep changes stagedgit reset --soft HEAD~1
# Undo last commit, keep changes in working dirgit reset --mixed HEAD~1
# Discard last commit and all changesgit reset --hard HEAD~1
# Unstage filegit reset HEAD filename.txt
# Reset to specific commitgit reset --hard a1b2c3d
```

Execution

Terminal window

```
git reset --soft HEAD~1
```

-   DANGEROUS if commits pushed to shared branch
-   Use on local commits only
-   \--hard irreversibly deletes changes

#### Safely revert commits

Creates new commit that undoes changes from specified commit. Safe for shared branches.

Code

Terminal window

```
# Create new commit reversing changesgit revert HEAD
# Revert specific commitgit revert a1b2c3d
# Revert multiple commitsgit revert --no-edit HEAD~3..HEAD
# Revert without committinggit revert -n HEAD
```

Execution

Terminal window

```
git revert HEAD
```

Output

Terminal window

```
[main b3c4d5e] Revert "Add feature" 1 file changed, 10 deletions(-)
```

-   Creates new commit (preserves history)
-   Safe for pushed commits
-   Opposite changes in new commit

### Restore and Checkout Files

Restore files to previous states without moving HEAD.

#### Accessibility

Explain when to use restore vs reset

#### Best Practices

-   Use restore for file-level changes
-   Review changes before discarding
-   Commit important work before discarding

#### Common Errors

-   **pathspec did not match:** Check file path and filename spelling

#### Keywords

restorecheckoutdiscardfilechanges

[Learn more](https://git-scm.com/docs/git-restore)

#### Discard changes in files

Restores files to their last committed state, discarding local changes.

Code

Terminal window

```
# Discard changes to file (checkout)git checkout -- filename.txt
# Discard changes (restore)git restore filename.txt
# Discard all changesgit restore .
# Restore from specific commitgit checkout a1b2c3d -- filename.txt
# Restore to previous versiongit restore --source=HEAD~1 filename.txt
```

Execution

Terminal window

```
git restore filename.txt
```

-   Does not affect commit history
-   Useful for discarding accidental changes
-   \--source specifies which commit to restore from

#### Unstage files

Removes files from staging area while keeping changes in working directory.

Code

Terminal window

```
# Unstage file (restore --staged)git restore --staged filename.txt
# Unstage all filesgit restore --staged .
# Alternative: resetgit reset HEAD filename.txt
# Unstage but keep changesgit reset HEAD filename.txt
```

Execution

Terminal window

```
git restore --staged filename.txt
```

-   Changes remain in working directory
-   Allows re-staging with modifications

## Advanced

Complex operations for power users and advanced workflows.

### Rebase and Cherry Pick

Rewrite history and apply selective commits.

#### Accessibility

Clear explanation of interactive rebase steps

#### Best Practices

-   Rebase only on local commits
-   Use interactive rebase to clean history before pushing
-   Cherry-pick for backporting fixes

#### Common Errors

-   **Cannot rebase with unresolved conflicts:** Resolve conflicts and run git rebase --continue

#### Keywords

rebasecherry-pickinteractivehistorycommit

[Learn more](https://git-scm.com/docs/git-rebase)

#### Rebase branch over another

Replays commits on top of another branch creating linear history instead of merge.

Code

Terminal window

```
# Rebase current branch onto maingit rebase main
# Interactive rebase for last 3 commitsgit rebase -i HEAD~3
# Rebase and squash commitsgit rebase -i HEAD~3# In editor: keep first 'pick', change others to 'squash'
# Abort rebase if problemsgit rebase --abort
# Continue after resolving conflictsgit rebase --continue
```

Execution

Terminal window

```
git rebase main
```

Output

Terminal window

```
First, rewinding head to replay your work on top of it...Applying: Add featureApplying: Fix tests
```

-   Creates new commit objects (changes hashes)
-   Never rebase pushed commits in shared branches
-   Interactive rebase (-i) allows editing commits

#### Cherry pick commits

Applies changes from specific commit to current branch, creating new commit.

Code

Terminal window

```
# Apply specific commit to current branchgit cherry-pick a1b2c3d
# Pick multiple commitsgit cherry-pick a1b2c3d x8y9z0a
# Pick range of commitsgit cherry-pick a1b2c3d..x8y9z0a
# Cherry-pick without committinggit cherry-pick -n a1b2c3d
# Abort if conflictsgit cherry-pick --abort
```

Execution

Terminal window

```
git cherry-pick a1b2c3d
```

Output

Terminal window

```
[main p3q4r5s] Add feature 1 file changed, 25 insertions(+)
```

-   Useful for backporting fixes
-   Creates new commits (different hashes)
-   Resolve conflicts same as merge

### Stash and Merge

Temporarily save work and integrate branches.

#### Accessibility

Explain when to use stash vs commit

#### Best Practices

-   Stash for switching context temporarily
-   Commit instead of stash when possible
-   Resolve conflicts carefully

#### Common Errors

-   **Your local changes would be overwritten:** Stash changes or commit before switching branches

#### Keywords

stashmergetemporarystorageconflicts

[Learn more](https://git-scm.com/docs/git-stash)

#### Stash changes

Temporarily saves uncommitted changes, cleaning working directory.

Code

Terminal window

```
# Stash current changesgit stash
# Stash with messagegit stash save "my work in progress"
# Stash including untracked filesgit stash -u
# List all stashesgit stash list
# Apply latest stashgit stash apply
# Apply and remove stashgit stash pop
# Apply specific stashgit stash apply stash@{0}
```

Execution

Terminal window

```
git stash
```

Output

Terminal window

```
Saved working directory and index state WIP on main: a1b2c3d Update docs
```

-   Stash stores changes in temporary storage
-   list shows all saved stashes
-   pop applies and removes stash

#### Handle merge conflicts

Handles merge conflicts by manual resolution and recommit.

Code

Terminal window

```
# Start merge (may hit conflicts)git merge feature
# View conflicted filesgit status
# View specific conflictgit diff
# After solving in editor:git add resolved-file.txtgit commit -m "Merge feature branch"
# Abort merge if necessarygit merge --abort
```

Execution

Terminal window

```
git merge feature
```

Output

Terminal window

```
Auto-merging file.txtCONFLICT (content): Merge conflict in file.txtAutomatic merge failed; fix conflicts and then commit the result.
```

-   Conflict markers indicate conflict regions
-   Edit files to remove markers and pick resolution
-   Stage and commit after resolution

## Remote Tracking

Manage remote repositories and tracking branches.

### Configure Remotes and Fetch

Set up and work with remote repositories.

#### Accessibility

Explain remote configuration and tracking relationships

#### Best Practices

-   Fetch before pushing to check for conflicts
-   Use --prune to keep local cache clean
-   Maintain upstream reference in forks

#### Common Errors

-   **Authentication failed:** Check remote URL and credentials/SSH keys

#### Keywords

remoteaddfetchtrackingupstream

[Learn more](https://git-scm.com/docs/git-fetch)

#### Manage remote repositories

Adds, removes, and manages remote repository references.

Code

Terminal window

```
# List all remotesgit remote
# List with URLsgit remote -v
# Add new remotegit remote add upstream https://github.com/original/repo.git
# Remove remotegit remote remove origin
# Rename remotegit remote rename origin old-origin
# Change remote URLgit remote set-url origin https://github.com/user/repo.git
```

Execution

Terminal window

```
git remote -v
```

Output

Terminal window

```
origin https://github.com/user/repo.git (fetch)origin https://github.com/user/repo.git (push)upstream https://github.com/original/repo.git (fetch)
```

-   origin is default remote (clone source)
-   upstream common for forked repositories
-   Separate fetch and push URLs possible

#### Fetch from remotes

Downloads remote branch updates without merging. Safe operation for syncing.

Code

Terminal window

```
# Fetch from default remotegit fetch
# Fetch from specific remotegit fetch origin
# Fetch from all remotesgit fetch --all
# Fetch specific branchgit fetch origin main
# Prune deleted remote branchesgit fetch --prune
# Fetch and fast-forwardgit fetch origin && git merge
```

Execution

Terminal window

```
git fetch --all
```

Output

Terminal window

```
Fetching originremote: Counting objects: 5, done.Unpacking objects: 100% (3/3), done.From github.com:user/repo   a1b2c3d..x8y9z0a  main       -> origin/main
```

-   Fetch updates remote tracking branches
-   \--all fetches from all remotes
-   \--prune removes deleted remote branches

### Tracking Branch Configuration

Set up and manage upstream tracking relationships.

#### Accessibility

Explain tracking branch benefits

#### Best Practices

-   Use -u when pushing new branches
-   Keep tracking branches updated
-   Use pull rebase for merging updates

#### Common Errors

-   **No tracking information for branch:** Set upstream with git branch -u or git push -u

#### Keywords

trackingupstreamset-upstreambranchrelationship

[Learn more](https://git-scm.com/book/en/v2/Git-Branching-Tracking-Branches)

#### Set up tracking branches

Establishes connection between local and remote branches for tracking.

Code

Terminal window

```
# Set upstream for current branchgit branch -u origin/main
# Set upstream when pushing new branchgit push -u origin feature
# Create tracking branch from remotegit checkout --track origin/feature
# Create with specific local namegit checkout -b my-feature origin/feature
# View tracking statusgit branch -vv
```

Execution

Terminal window

```
git branch -vv
```

Output

Terminal window

```
main    a1b2c3d [origin/main] Update docsfeature x8y9z0a [origin/feature] Add feature
```

-   Tracking enables git pull to work without arguments
-   Shows ahead/behind status
-   \-vv shows verbose with tracking branch

#### Update tracking branches

Pulls and integrates remote changes using tracking relationship.

Code

Terminal window

```
# Pull current branch (requires tracking)git pull
# Pull specific branchgit pull origin main
# Pull with rebasegit pull --rebase
# See what will be pulledgit fetch && git log --oneline origin/main..main
```

Execution

Terminal window

```
git pull --rebase
```

Output

Terminal window

```
From github.com:user/repo   a1b2c3d..x8y9z0a  main       -> origin/mainFast-forward
```

-   Tracking branch simplifies pull/push
-   \--rebase preferred for linear history

## Extras & Tips

Advanced utilities and best practices for Git workflows.

### Bisect and Debugging

Find problematic commits using binary search.

#### Accessibility

Clear step-by-step bisect process

#### Best Practices

-   Use bisect for large histories
-   Write good commit messages for blame readability
-   Use blame to understand code context

#### Common Errors

-   **No commits marked good:** Mark at least one good and one bad commit

#### Keywords

bisectdebugfindregressionblame

[Learn more](https://git-scm.com/docs/git-bisect)

#### Use git bisect

Binary search through commits to find where bug was introduced.

Code

Terminal window

```
# Start bisect sessiongit bisect start
# Mark current commit as badgit bisect bad
# Mark known good commitgit bisect good a1b2c3d
# Test current state and markgit bisect good  # or git bisect bad
# Continue until found# ... (git will narrow down)
# Reset after finding bad commitgit bisect reset
```

Execution

Terminal window

```
git bisect start
```

Output

Terminal window

```
Bisecting: 5 revisions left to test after this (roughly 2 steps)[a1b2c3d] Commit message
```

-   Good for finding a regression in a long history
-   Automatically narrows search space
-   Mark commits as good or bad

#### Find changes with blame

Annotates each line with commit hash, author, and date that changed it.

Code

Terminal window

```
# Show who changed each linegit blame filename.txt
# Show abbreviated blamegit blame -s filename.txt
# Show blame for specific rangegit blame -L 10,20 filename.txt
# Show blame with commit dategit blame --date=short filename.txt
```

Execution

Terminal window

```
git blame filename.txt
```

Output

Terminal window

```
a1b2c3d (John Doe 2025-01-15 10:30:00 +0000) line contentx8y9z0a (Jane Smith 2025-02-01 14:22:00 +0000) line content
```

-   Useful for tracking origin of bugs
-   Helps understand code history

### Signing and Maintenance

GPG signing commits and repository cleanup.

#### Accessibility

Explain security benefits of signing

#### Best Practices

-   Sign commits in professional projects
-   Run gc periodically to compress the repository
-   Use clean carefully to avoid deleting files

#### Common Errors

-   **no default secret key:** Configure GPG key with git config user.signingkey

#### Keywords

signgpgverifycleanupgarbage

[Learn more](https://git-scm.com/docs/git-commit)

#### Sign commits with GPG

Signs commits with GPG key for authentication and verification.

Code

Terminal window

```
# Configure GPG signinggit config --global user.signingkey YOUR_GPG_KEY_ID
# Sign individual commitgit commit -S -m "Signed commit"
# Sign all commits by defaultgit config --global commit.gpgSign true
# Verify signed commitgit verify-commit a1b2c3d
# Show GPG signature in loggit log --show-signature
```

Execution

Terminal window

```
git commit -S -m "Signed commit"
```

Output

Terminal window

```
[main a1b2c3d] Signed commit 1 file changed, 10 insertions(+)
```

-   Requires GPG key setup
-   \-S flag signs commit
-   GitHub shows verification badge for signed commits

#### Repository maintenance

Performs repository maintenance and cleanup operations.

Code

Terminal window

```
# Remove empty commitsgit gc
# Run full optimizationgit gc --aggressive
# Clean untracked filesgit clean -fd
# View repo sizegit count-objects -v
# Remove large files from historygit filter-branch --tree-filter 'rm -f large-file.bin'
```

Execution

Terminal window

```
git gc
```

Output

Terminal window

```
Counting objects, done.
```

-   gc compresses repository (safe)
-   clean removes untracked files
-   filter-branch rewrites history (careful!)

### Aliases and Shortcuts

Create custom commands and shorten common workflows.

#### Accessibility

Provide commonly used aliases

#### Best Practices

-   Create aliases for your most used commands
-   Share useful aliases with team
-   Keep simple aliases short and write complex ones out in full

#### Common Errors

-   **unknown command:** Check alias is defined with git config --list

#### Keywords

aliasshortcutcustomworkflowproductivity

[Learn more](https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases)

#### Create command aliases

Creates shorthand commands for frequently used git operations.

Code

Terminal window

```
# Create short aliasgit config --global alias.st statusgit config --global alias.co checkoutgit config --global alias.br branchgit config --global alias.ci commit
# Create complex aliasesgit config --global alias.log-graph \'log --graph --all --oneline --decorate'
# Create unstage aliasgit config --global alias.unstage 'restore --staged'
# Create last-commit aliasgit config --global alias.last 'log -1 HEAD'
```

Execution

Terminal window

```
git config --global alias.st status
```

-   Aliases stored in ~/.gitconfig
-   Saves time on repetitive commands
-   Can create very complex aliases

#### Useful workflow aliases

Simplifies common workflows with custom commands.

Code

Terminal window

```
# Amend without editing messagegit config --global alias.amend 'commit --amend --no-edit'
# Pull with rebasegit config --global alias.pr 'pull --rebase'
# List branches by dategit config --global alias.branches \'branch -a --sort=-committerdate'
# Show recent branchesgit config --global alias.recent 'for-each-ref --sort=-committerdate'
```

Execution

Terminal window

```
git amend
```

Output

Terminal window

```
[main a1b2c3d] Commit message
```

-   Create aliases for operations you use frequently
-   Shorter commands mean fewer typos

Was this useful?

## Tags

#Git#Version Control#Branches#Commits#Collaboration#SCM#GitHub#GitLab

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Git&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit&title=Git&summary=Git%20is%20a%20distributed%20version%20control%20system%20for%20tracking%20code%20changes%2C%20collaborating%20with%20teams%2C%20and%20managing%20project%20history.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Git%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit&text=Git "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit&title=Git "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit&t=Git "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit&media=&description=Git%20is%20a%20distributed%20version%20control%20system%20for%20tracking%20code%20changes%2C%20collaborating%20with%20teams%2C%20and%20managing%20project%20history. "Share on Pinterest")[Email](<mailto:?subject=Git&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgit>)

## Comments

## You might also enjoy

More posts on similar topics

## [Python Virtual Environments Cheatsheet](/cheatsheets/python-venv)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Python
-   Development Tools
-   Dependency Management

A fast reference for keeping Python projects isolated and reproducible. It covers creating and activating environments with venv, installing packages with pip, locking dependencies with requirements f

#Python#Virtualenv#Pip+5 tags

[read more](/cheatsheets/python-venv)

## [Screen](/cheatsheets/screen)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Screen
-   Tools
-   Development
-   System Administration

Getting started GNU Screen is a terminal multiplexer that gives you:Sessions: Full terminal environments that persist even if you disconnect Windows: Multiple terminals (tabs) within

#Screen#Terminal Multiplexer#Sessions+2 tags

[read more](/cheatsheets/screen)

## [Tmux](/cheatsheets/tmux)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Tmux
-   Tools
-   Development
-   System Administration

Tmux is a terminal multiplexer for managing multiple terminal sessions, windows, and panes within a single screen. This cheatsheet covers the commands, keybindings, and configuration options for every

#Tmux#Terminal Multiplexer#Sessions+3 tags

[read more](/cheatsheets/tmux)

## [Vim](/cheatsheets/vim)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Editor
-   Text Editor
-   Terminal
-   Command Line
-   Productivity

Vim is a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems. The sections below cover Vim commands, sho

#Editor#Vim#Text Editor+3 tags

[read more](/cheatsheets/vim)

## [VS Code](/cheatsheets/vscode)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Editor
-   Text Editor
-   Developer Tools
-   Productivity
-   Programming
-   Shortcuts

A quick reference for Visual Studio Code: keyboard shortcuts, editor features, and working habits for editing and navigation.

#VS Code#Visual Studio Code#Keyboard Shortcuts+3 tags

[read more](/cheatsheets/vscode)

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

6 related posts
