Git Cheat Sheet

Contents
Setup
- User name:
git config --global user.name "[firstname lastname]" - Email:
git config --global user.email "[valid-email]" - Color:
git config --global color.ui auto
Initialization and cloning
- Make your current folder a git repo:
git init - Clone a repo:
git clone [url]
Staging and commits
- Get status of staged, unstages and untracked files:
git status - Add files to staging:
git add [file] - Remove a file from staging:
git reset [file] - Remove a file from staging and remove all changes:
git reset --hard [file] - Differences in files that are modified but not staged:
git diff - Differences in files that are staged but not committed:
git diff --staged - Commit changes:
git commit -m "[message]" - Commit only specific portion of a file:
git add -p [file]
Note: Git will go into interactive mode and prompt options for actions on each hunk. - Add current staged changes to the previous commit:
git commit --amend
Note: Avoid amending a commit after they’ve been pushed. - Undo all changes of the latest commit:
git revert HEAD - Undo all changes of a specific commit:
git revert [commit-sha] - Change a file but never commit it (hide from git):
git update-index --skip-worktree [file]
Note: Used to avoid accidentally committing config files (for example DB credentials) that are modified for local setup. - Undo previous command (unhide from git):
git update-index --no-skip-worktree [file]
Branch and merge
- List all branches and highlight current branch:
git branch - Switch to another branch:
git checkout [branch-name] - Create a new branch and switch to it:
git checkout -b [branch name] - Delete a branch:
git branch -d [branch-name] - Merge another branch to current branch:
git merge [branch-name] - Rebase the current branch to the top of master:
git rebase master
Tags
- List all tags:
git tag - Create a tag for current commit:
git tag [tag-name] - Create a tag for specific commit:
git tag [tag-name] [commit-sha] - Delete a tag:
git tag -d [tag-name]
Inspect changes
- Commit history of current branch:
git log - Show commits that changed a file:
git log --follow [file] - Show commit history as a graph:
git log --graph --oneline
Interacting with remote repo
- Add a git URL as remote:
git remote add origin [url] - Get all changes from remote branch:
git pull - Send all local changes to remote branch:
git push - Merge a remote branch to current:
git merge origin\[branch-name]
Temporary commits
- Save all changes:
git stash - Restore changes from stash:
git stash pop - Discard the top of stash:
git stash drop