Git Cheat Sheet: A Comprehensive Guide to Git Commands

Git Cheat Sheet

Getting Started

git clone "existing repo" Clone the repository

git init Create a new local repository

Branches

git branch List all local branches

git branch -r List all remote branches

git branch -d "BRANCH" Remove branch

git branch -m "BRANCH" Rename branch

git remote show "Remote" List all branches for specific remote

git checkout "BRANCH" Switch to branch “BRANCH”

git checkout -b "BRANCH" Create and switch to a new branch “BRANCH”

git checkout -b "BRANCH" "REMOTE/BRANCH" Create branch based on remote branch

git merge "BRANCH" Merges the specified branch to the current branch

Make a Change

git add . Add (stage) all the files which are modified

git add "FILE.cpp" Add (stage) the single file which is modified

git commit -m "commit message" Commit all the added (staged) files to the local Git

Rewriting History

git commit --amend -m "new_message" Edit the last commit message

git commit --amend Edit the last commit

git commit --amend --no-edit Edit the last commit but use the same commit message

git reset HEAD~1 Undo last commit (add --hard to reset changes)

git reset "COMMIT-ID" Reset the head to the mentioned commit-id

git rebase "BRANCH" Applies the commits of the specified branch on top of the current branch

git revert "COMMIT-ID" Reverts the changes introduced by the specified commit by creating a new commit that undoes those changes

Interactive Rebase

git rebase -i "COMMIT-ID" Interactive rebase allows you to modify or reorder commits interactively

  • pick: Keep the commit as is.
  • reword: Keep the commit but modify the commit message.
  • edit: Pause the rebase and allow you to modify the commit content.
  • squash: Merge the commit with the previous commit and combine their messages.
  • fixup: Merge the commit with the previous commit but discard its message.
  • drop: Remove the commit from the branch entirely.

git rebase --skip Skips the current commit and moves to the next one during a rebase

Status

git log Shows the commit history of the current branch

git status List all the files which are staged, unstaged and untracked

git diff Shows the difference of what is changed but not staged

Remote

git remote add [alias] [URL] Add the Git remote URL as alias

git remote -v Shows the name and URL of the remote repositories

Synchronize

git push -u origin "BRANCH" Pushes the local branch to the remote branch

git fetch Fetches all the remote repositories

git fetch "BRANCH" Fetches the particular branch

git pull "BRANCH" Fetch the remote copy of the current branch and merge it into the local branch

Cherry Picking

git cherry-pick "COMMIT_ID" Applies the specified commit to the current branch

Stash (temporarily store the changes instead of doing commit)

git stash Save staged/modified changes

git stash list List stack of stash list

git stash pop Brings back the stashed changes