Skip to main content

Git Commands - Quick and Dirty

An Overview of Useful Git Commands

Git is a popular open source Version Control System that allows decentralized management of project repositories.

Here’s a quick and dirty guide to common git commands:

This is NOT A TUTORIAL on how to use git. It’s meant as a quick way to look up git commands. Please do not use these commands if you’re just learning to use git; kindly follow these links at the bottom of this post to get Git guides and tutorials.

Git Quick Commands Listing

Git Configuration

Add your name and email (baked into each commit made):

git config --global user.name "Your Name"
git config --global user.email you@example.com

Configure text editor to use (e.g. to use vim)

git config --global core.editor vim

Adding colors

git config --global color.diff auto
git config --global color.status auto
git config --global color.branch auto

Set up GPG keys to cryptographically sign your commits for enhanced security and verification.

Listing all configurations set

git config --list

Modern Git defaults and performance optimizations for a better development experience.

Essential Git Operations

Initialize a repository

# initialize a new git repository
git init

# add all files in the current directory to the new repo
git add .

# adds a commit to the new repo
git commit -m "Initial commit"

Cloning a remote repository

# clone repository via https
git clone https://github.com/USERNAME/REPOSITORYNAME.git

# clone repository via ssh
git clone username@host:/path/to/repository

Adding files to repository

# add all in the current directory to staging area
git add .

# Add all files (new, modified,deletions) to index (stage)
git add -A # perfoms git add .; git add -u

# Add specific files to staging area
git add filename.txt

Listing files and tracking status

# List tracked files
git ls-files

# List all untracked files
git ls-files --others  
# add --directory for directories

Removing a file from tracking

# Modern: Unstage a file but preserve its contents
git restore --staged filename

# Legacy: Unstage a file (still widely used)
git reset filename

# Remove files from index, stage its deletion from HEAD
git rm filename

To prevent tracking of files; add the file or directory to the .gitignore file (each file/directory on a new line).

Committing

# will prompt for a commit message in the configured text editor
git commit  

# shorthand for adding a message to the commit
git commit -m "Fixes stuff x"

# Quick Add & Commit - add all modified files and commit
git commit -am "The commit message here"

# Status of files in index vs Working directory
git status

Stage changes selectively by reviewing each change before adding it to the commit.

Resetting and Reverting Repo

Revert to previous commit (graceful - does not delete history)

# git revert [SHA-1]
git revert HEAD

Modern File Operations (Git 2.23+)

# Discard changes in working directory (preferred)
git restore myfile

# Unstage file (remove from staging area)
git restore --staged myfile

# Restore file from specific commit
git restore --source=HEAD~1 myfile

Legacy File Operations (still widely used)

# Undo changes to a file (legacy - use 'restore' instead)
git checkout -- myfile

# Unstage file (legacy - use 'restore --staged' instead)
git reset myfile

Reset to previous state: Do not use if already commited to shared remote

# git reset --hard [SHA-1] # Reset completely delete history and staged
git reset --hard HEAD

# git reset --soft [SHA-1] # does not touch staging area or working tree
git reset --soft HEAD

Re-clone from a remote repository; will loose changes not in the remote. (e.g if local git corrupt)

rm -fr .git
git init
git remote add origin [your-git-remote-url]
git fetch
git reset --mixed origin/master
git branch --set-upstream-to=origin/master master  

Git Branches

Modern Branch Operations (Git 2.23+)

# Switch to existing branch (preferred over checkout)
git switch branchname

# Create and switch to new branch
git switch -c branchname

# Switch to previous branch
git switch -

Legacy Branch Operations (still widely used)

# Create local branch
git branch branchname

# Move/switch to a branch (legacy - use 'switch' instead)
git checkout branchname

# Create and switch to branch (legacy)
git checkout -b branchname

# Fetch file from another branch
git checkout branchtwo -- path/to/file

# Push to a new remote branch, e.g. if remote name is origin
git push -u origin branchname

# Delete Local Branch
git branch -d branchname

# Delete remote branch
git push origin :branchname

# Forcefully delete from both local and remote
git branch -D branchname

# Update local database of remote branches (prune deleted)
git fetch -p

# Checkout branches with latest commits #esp for cleaning old branches
git for-each-ref --sort=-committerdate --format='%(refname:short) %(committerdate:short)'

Best practices for naming branches to keep your repository organized and maintainable.

Git merge

Before merging, checkout to branch you want to merge to:

git checkout master

# Merge local branch
git merge branchname

# Always generate merge commit even on fast-forward
git merge --no-ff branchname

# List branches that have been merged to current branch (e.g master)
git branch --merged

git branch --no-merged  #list branches that haven't been merged to current

# Delete merged branches
git branch --merged | xargs git branch -d

Merge remote branch

# Update the remote
git fetch origin

# Merge remote branch
git merge origin/branchname

# SHORTCUT - Fetch and merge tracked branch
git pull

Rewriting Git History

NOTE: Do not rewrite public commits/history

# Updates staged changes to previous commit message.(i.e replaces the previous commit)
git commit --amend

Git Rebase

Moving a branch to a new base commit (an ID, a branch name, a tag, or a relative reference to HEAD)

git rebase v0.2.2
# NOTE - all commits v0.2.2..HEAD will be rewritten

Advanced technique for rewriting commit history - squash, reorder, and edit multiple commits.

Working with Remotes

Adding remote - Connecting local repo with a remote repo (for example a repo on github)

git remote add origin https://github.com/USERNAME/REPOSITORY.git
#git remote add [name] [repourl]

# Verify remotes - List existing remotes
git remote -v

# List all remote branches
git branch -r

# Remove remote
git remote remove origin

# Replace remote url
git remote set-url origin https://github.com/USERNAME/REPOSITORY2.git

# To check out commits on an upstream master
git log --oneline master..origin/master

# Merge remote branch eg upstream master into current branch
git merge origin/master

# Rebase (fetch remote branch and merge)
git pull --rebase remote

# Fetch all remotes
git fetch --all #git fetch [remotename] #to fetch single remote

#push to a new remote branch
git push -u origin branchname

Stashing

Stash - Store modified tracked files and staged changes on a stach for reapplying later

#push stash onto stack
git stash

# Store stash with message
git stash save 'A custom message'

# List stored stashes
git stash list

# Reapply most recent stash
git stash apply
#for older stashes pick from list e.g git stash apply stash@{1}

# Remove stash from stack
git stash drop stash@{0}
#drops stash reference or if no parameter drops latest stash

# Clear all stashes
git stash clear

# Apply latest stash and remove from stack
git stash pop

Useful Commands

History - Checkout the history of your commits

git log --oneline --graph --decorate --all --color

# Filter logs
git log --author=author
git log --after="MMM DD YYYY"
git log --before="MMM DD YYYY"
git log --grep REGEXP  # Commits with matches to regular expression

#list history of file
git log --follow filename

# Show changes to file
git whatchanged file

# Show author of each line in file
git blame file

# Search through repo history
git rev-list --all | xargs git grep -F 'searchstring'
#git rev-list --all | xargs git grep 'REGEX' #to search for regular expression

Diff - Compare states

# Compare two commits
git diff master..upstream/branchname
#git diff HEAD~2..HEAD~1

# Compare staged changes to your last commit
git diff --cached

# Compare working directory to your last commit
git diff HEAD

Tagging

#annotated tag
git tag -a v1.5 -m 'Message Here'

#lightweight tag
git tag v1.5.2
#to create lightweight tag; don't supply the -a, -s, or -m option

#list tags
git tag

#show tag and related commit
git show v1.2

# Tag older commit
git tag -a v2 9fceb02 -m "Message here"
# git tag -a v1.2 [SHA-1] -m "[your message]"

# Rename tag
git tag newtag oldtag
git tag -d oldtag
git push origin :refs/tags/oldtag
git push --tags

# Adding a message to an existing tag
git tag tagname tagname -f -m "the message"
# creates a tag of the same name with a message and overwrites old tag

# Push referenced tags along with branches
git push --follow-tags

Cleaning

# Perform clean dry-run - show files to delete
git clean -n

# Remove all untracked files from working copy
git clean -f

# Remove all untracked and ignored files and directories from working copy
git clean -fxd

# Cleanup unnecessary files and optimize the local repository
git gc #calls git prune with prunes loose objects older than 2wks

git gc --prune=all #prunes all loose objects

Useful Git Files

Configuration files that control Git behavior:

  • .gitignore - files/patterns to exclude from tracking
  • .gitattributes - per-path attributes (line endings, GitHub language detection)
  • .mailmap - map author/committer names and emails
  • .gitmodules - submodule configuration
  • .gitmessage - commit message template
  • .git-blame-ignore-revs - commits to ignore in blame view
  • .gitkeep - placeholder to track empty directories

Official Resources

Official Documentation:

Interactive Learning:

Official Cheat Sheets:

Published: · Updated:
git cheatsheet
· Edit this page