Git
Git is a distributed version control system for tracking code changes, collaborating with teams, and managing project history.
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.
Set user identity
Sets the name and email used for commit authorship. Use --global for all repositories or --local for specific project.
# 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"git config --global user.nameJohn 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.
# 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 truegit config --global --listuser.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.
Initialize a new repository
Creates a new Git repository in current directory with a hidden .git folder containing repository metadata.
# 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=maingit initInitialized 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.
# 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.gitgit clone https://github.com/user/repo.gitCloning 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.
Stage and commit changes
Adds modified files to staging area and creates a commit with descriptive message.
# 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"git add . && git commit -m "Update code"[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.
# 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 nowgit commit --amend -m "Updated message"[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.
Push changes to remote
Uploads local commits to the remote repository on the specified branch.
# 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.0git push origin mainEnumerating 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.
# 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 --allgit pull origin mainFrom 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.
Check repository status
Shows which files are modified, staged, or untracked in current working directory.
# View current statusgit status
# Short status formatgit status -s
# Include untracked filesgit status --include-untrackedgit status -sM 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.
# View unstaged changesgit diff
# View staged changesgit diff --staged
# View changes in specific filegit diff filename.txt
# View changes between commitsgit diff HEAD~2 HEADgit diff --stageddiff --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.
Create and switch branches
Creates a new branch either from current HEAD or specific commit and optionally switches to it.
# 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-localgit checkout -b feature-newSwitched 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.
# 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-3git branch -d feature-newDeleted 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.
Switch between branches
Changes working directory to selected branch. Can create new branch at same time.
# 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 -git switch mainSwitched to branch 'main'- git switch is newer, alias for checkout
- Saved 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.
# 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 --abortgit merge featureMerge 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.
List branches
Lists all branches with option to show last commit for each branch.
# 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-mergedgit branch -v* 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.
View commit history
Shows commit history in selected format. Use --oneline for concise view, --graph for branch visualization.
# 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 --statgit log --oneline -n 5a1b2c3d 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.
# 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.txtgit log --author="John" --oneline --graph* 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.
Reference commits with revisions
Shows specific commits using HEAD references and relative positioning.
# 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.0git show HEAD~1commit 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.
# 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..x8y9z0agit log main..feature --onelinep5q6r7s 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.
Reset changes
Moves HEAD to previous state. --soft keeps changes staged, --mixed unstages, --hard discards all.
# 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 a1b2c3dgit 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.
# 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 HEADgit revert HEAD[main b3c4d5e] Revert "Add feature" 1 file changed, 10 deletions(-)- Creates new commit (preserve history)
- Safe for pushed commits
- Opposite changes in new commit
Restore and Checkout Files
Restore files to previous states without moving HEAD.
Discard changes in files
Restores files to their last committed state, discarding local changes.
# 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.txtgit 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.
# 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.txtgit 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.
Rebase branch over another
Replays commits on top of another branch creating linear history instead of merge.
# 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 --continuegit rebase mainFirst, 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.
# 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 --abortgit cherry-pick a1b2c3d[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.
Stash changes
Temporarily saves uncommitted changes, cleaning working directory.
# 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}git stashSaved 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.
# 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 --abortgit merge featureAuto-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.
Manage remote repositories
Adds, removes, and manages remote repository references.
# 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.gitgit remote -vorigin 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.
# 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 mergegit fetch --allFetching 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.
Set up tracking branches
Establishes connection between local and remote branches for tracking.
# 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 -vvgit branch -vvmain 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.
# 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..maingit pull --rebaseFrom 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.
Use git bisect
Binary search through commits to find where bug was introduced.
# 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 resetgit bisect startBisecting: 5 revisions left to test after this (roughly 2 steps)[a1b2c3d] Commit message- Efficient Way to find regression
- 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.
# 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.txtgit blame filename.txta1b2c3d (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.
Sign commits with GPG
Signs commits with GPG key for authentication and verification.
# 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-signaturegit commit -S -m "Signed commit"[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.
# 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'git gcCounting objects, done.- gc compresses repository (safe)
- clean removes untracked files
- filter-branch rewrites history (careful!)
Aliases and Shortcuts
Create custom commands and optimize workflows.
Create command aliases
Creates shorthand commands for frequently used git operations.
# 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'git config --global alias.st status- Aliases stored in ~/.gitconfig
- Saves time on repetitive commands
- Can create very complex aliases
Useful workflow aliases
Streamlines common workflows with custom commands.
# 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'git amend[main a1b2c3d] Commit message- Create aliases for operations you use frequently
- Improves productivity and reduces errors