Git Cheat Sheet
Git is the free and open source distributed version control system that's responsible for everything GitHub related that happens locally on your computer. This cheat sheet features the most important and commonly used Git commands for easy reference.
Table of Contents
- [[#Setup]]
- [[#Setup & Init]]
- [[#Stage & Snapshot]]
- [[#Branch & Merge]]
- [[#Merge Techniques]]
- [[#Inspect & Compare]]
- [[#Share & Update]]
- [[#Tracking Path Changes]]
- [[#Rewrite History]]
- [[#Advanced Rebasing Techniques]]
- [[#Temporary Commits]]
- [[#Ignoring Patterns]]
- [[#Undoing Changes]]
- [[#Git Workflows]]
Git Workflows
Common Git Workflows
Feature Branch Workflow
- Create a new branch for each feature:
git checkout -b feature-name - Make changes and commit:
git add,git commit - Push branch to remote:
git push -u origin feature-name - Create pull request (on GitHub/GitLab)
- After review, merge to main branch
Gitflow Workflow
- Main branches:
main(production),develop(integration) - Support branches:
feature/*,release/*,hotfix/* - Features start from
developand merge back todevelop - Releases branch off
developand merge to bothmainanddevelop - Hotfixes branch off
mainand merge to bothmainanddevelop
Setup
Configuring user information used across all local repositories
# Set a name that is identifiable for credit when reviewing version history
git config --global user.name "[firstname lastname]"
# Set an email address that will be associated with each history marker
git config --global user.email "[valid-email]"
# Set automatic command line coloring for Git for easy reviewing
git config --global color.ui auto
# Create shortcut for a Git command
git config --global alias.<alias-name> <git-command>
# E.g. alias.glog "log --graph --oneline" will set "git glog" equivalent to "git log --graph --oneline"
# Set text editor used by commands for all users on the machine
git config --system core.editor <editor>
# <editor> arg should be the command that launches the desired editor (e.g., vi)
# Open the global configuration file in a text editor for manual editing
git config --global --edit
Setup & Init
Configuring user information, initializing and cloning repositories
# Initialize an existing directory as a Git repository
git init [directory]
# Clone repo located at <repo> onto local machine
# Original repo can be located on the local filesystem or on a remote machine via HTTP or SSH
git clone [url]
Stage & Snapshot
Working with snapshots and the Git staging area
# Show modified files in working directory, staged for your next commit
git status
# Add a file as it looks now to your next commit (stage)
git add [file]
# Stage all changes in <directory> for the next commit
# Replace <directory> with a <file> to change a specific file
git add [directory]
# Unstage a file while retaining the changes in working directory
git reset [file]
# Diff of what is changed but not staged
git diff
# Show difference between working directory and last commit
git diff HEAD
# Diff of what is staged but not yet committed
git diff --staged
# Show difference between staged changes and last commit
git diff --cached
# Commit your staged content as a new commit snapshot
git commit -m "[descriptive message]"
# Commit the staged snapshot, but instead of launching
# a text editor, use <message> as the commit message
git commit -m "<message>"
# Replace the last commit with the staged changes and last commit combined
# Use with nothing staged to edit the last commit's message
git commit --amend
Branch & Merge
Isolating work in branches, changing context, and integrating changes
# List your branches. A * will appear next to the currently active branch
git branch
# List all of the branches in your repo. Add a <branch> argument to
# create a new branch with the name <branch>
git branch [branch-name]
# Create a new branch at the current commit
git branch [branch-name]
# Switch to another branch and check it out into your working directory
git checkout [branch]
# Create and check out a new branch named <branch>
# Drop the -b flag to checkout an existing branch
git checkout -b [branch]
# Show all commits in the current branch's history
git log
Merge Techniques
Git offers various ways to integrate changes from one branch into another.
# Standard merge - creates a new commit that combines changes from both branches
git merge [branch]
# Merge <branch> into the current branch
git merge <branch]
# Fast-forward merge when possible (only when branch being merged is directly ahead)
git merge --ff [branch]
# Always create a merge commit, even if a fast-forward would be possible
git merge --no-ff [branch]
# Only perform merge if it can be resolved as a fast-forward
git merge --ff-only [branch]
# Abort merge in case of conflicts
git merge --abort
Merge Conflict Resolution
When merge conflicts occur:
- Git marks conflicts in the files
- Use
git statusto see which files have conflicts - Edit the files to resolve conflicts manually
- Use
git addto mark conflicts as resolved - Complete the merge with
git commit
# Tool to help resolve merge conflicts
git mergetool
# After resolving conflicts, commit the merge
git commit -m "Merge branch '[branch]'"
Inspect & Compare
Examining logs, diffs and object information
# Show the commit history for the currently active branch
git log
# Display the entire commit history using the default format
# For customization see additional options
git log
# Limit number of commits by <limit>
# E.g. "git log -5" will limit to 5 commits
git log -<limit>
# Condense each commit to a single line
git log --oneline
# Display the full diff of each commit
git log -p
# Include which files were altered and the relative number of
# lines that were added or deleted from each of them
git log --stat
# Search for commits by a particular author
git log --author="<pattern>"
# Search for commits with a commit message that
# matches <pattern>
git log --grep="<pattern>"
# Show commits that occur between <since> and <until>
# Args can be a commit ID, branch name, HEAD, or any other kind of revision reference
git log <since>..<until>
# Only display commits that have the specified file
git log -- <file>
# --graph flag draws a text based graph of commits on left side of commit msgs
# --decorate adds names of branches or tags of commits shown
git log --graph --decorate
# Show the commits on branchA that are not on branchB
git log branchB..branchA
# Show the commits that changed file, even across renames
git log --follow [file]
# Show the diff of what is in branchA that is not in branchB
git diff branchB...branchA
# Show any object in Git in human-readable format
git show [SHA]
Share & Update
Retrieving updates from another repository and updating local repos
# Add a git URL as an alias
git remote add [alias] [url]
# Create a new connection to a remote repo
# After adding a remote, you can use <name> as a shortcut for <url> in other commands
git remote add <name> <url>
# Fetch down all the branches from that Git remote
git fetch [alias]
# Fetches a specific <branch>, from the repo
# Leave off <branch> to fetch all remote refs
git fetch <remote> <branch>
# Merge a remote branch into your current branch to bring it up to date
git merge [alias]/[branch]
# Merge a remote branch into your current branch to bring it up to date
git merge [alias]/[branch]
# Transmit local branch commits to the remote repository branch
git push [alias] [branch]
# Push the branch to <remote>, along with necessary commits and
# objects. Creates named branch in the remote repo if it doesn't exist
git push <remote> <branch>
# Forces the git push even if it results in a non-fast-forward merge
# Do not use the --force flag unless you're absolutely sure you know what you're doing
git push <remote> --force
# Push all of your local branches to the specified remote
git push <remote> --all
# Tags aren't automatically pushed when you push a branch or use the
# --all flag. The --tags flag sends all of your local tags to the remote repo
git push <remote> --tags
# Fetch and merge any commits from the tracking remote branch
git pull
# Fetch the specified remote's copy of current branch and
# immediately merge it into the local copy
git pull <remote>
# Fetch the remote's copy of current branch and rebase it into the local copy
# Uses git rebase instead of merge to integrate the branches
git pull --rebase <remote>
Tracking Path Changes
Versioning file removes and path changes
# Delete the file from project and stage the removal for commit
git rm [file]
# Delete the file from project and stage the removal for commit
git rm [file]
# Change an existing file path and stage the move
git mv [existing-path] [new-path]
# Change an existing file path and stage the move
git mv [existing-path] [new-path]
# Show all commit logs with indication of any paths that moved
git log --stat -M
# Show all commit logs with indication of any paths that moved
git log --stat -M
Rewrite History
Rewriting branches, updating commits and clearing history
# Clear staging area, rewrite working tree from specified commit
git reset --hard [commit]
# Reset staging area to match most recent commit,
# but leave the working directory unchanged
git reset
# Reset staging area and working directory to match most recent
# commit and overwrites all changes in the working directory
git reset --hard
# Move the current branch tip backward to <commit>, reset the
# staging area to match, but leave the working directory alone
git reset <commit>
# Same as previous, but resets both the staging area & working directory to
# match. Deletes uncommitted changes, and all commits after <commit>
git reset --hard <commit>
# Show a log of changes to the local repository's HEAD
# Add --relative-date flag to show date info or --all to show all refs
git reflog
Advanced Rebasing Techniques
Rebasing allows you to modify your commit history in various ways.
# Apply any commits of current branch ahead of specified one
git rebase [branch]
# Rebase the current branch onto <base>
# <base> can be a commit ID, branch name, a tag, or a relative reference to HEAD
git rebase <base>
# Interactively rebase current branch onto <base>
# Launches editor to enter commands for how each commit will be transferred to the new base
git rebase -i <base>
Interactive Rebase Options
When doing an interactive rebase, you can use several commands:
pick- Keep the commit as isreword- Keep the commit but change the messageedit- Keep the commit but stop to amendsquash- Combine this commit with the previous one and merge commit messagesfixup- Like squash, but discard this commit's messagedrop- Remove the commit entirely
Rebase vs Merge
- Rebase: Creates a linear history by moving your local changes onto the tip of the upstream branch
- Merge: Preserves history exactly as it happened with a merge commit
Temporary Commits
Temporarily store modified, tracked files in order to change branches
# Save modified and staged changes
git stash
# Save modified and staged changes
git stash
# List stack-order of stashed file changes
git stash list
# List stack-order of stashed file changes
git stash list
# Write working from top of stash stack
git stash pop
# Write working from top of stash stack
git stash pop
# Discard the changes from top of stash stack
git stash drop
# Discard the changes from top of stash stack
git stash drop
Ignoring Patterns
Preventing unintentional staging or committing of files
# System wide ignore pattern for all local repositories
git config --global core.excludesfile [file]
Save a file with desired patterns as .gitignore with either direct string matches or wildcard globs:
logs/
*.notes
pattern*/
Common .gitignore Patterns
# Dependencies
node_modules/
vendor/
.npm
# Build outputs
build/
dist/
out/
# Environment files
.env
.env.local
.env.*.local
# IDE specific files
.idea/
.vscode/
*.sublime-project
*.sublime-workspace
# OS files
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Testing
coverage/
.nyc_output/
# Temporary files
*.tmp
*.bak
*.swp
Undoing Changes
# Create new commit that undoes all of the changes made in <commit>
# then apply it to the current branch
git revert <commit>
# Remove <file> from the staging area, but leave the working directory unchanged
# This unstages a file without overwriting any changes
git reset <file>
# Shows which files would be removed from working directory
# Use the -f flag in place of the -n flag to execute the clean
git clean -n