Git cheat sheet

Reference commands for the git version-control system.
  1. Commits
  2. Undo changes
  3. Merge
  4. Clean
  5. Remotes
  6. Branches
  7. Tags
  8. Submodules
  9. Large file storage
  10. References

Commits

Quick commit, with a single line message:

git commit -m "message"

Longer commit, supporting paragraphs. This will open your text editor:

git commit

Amend a commit:

git commit --amend

Undo changes

Undo last commit:

git reset --soft HEAD~1
git reset --hard HEAD~1

Remove from repo:

git rm -rf *

Unstage a directory:

git rm --cached -r dir

Abort a merge:

git merge --abort

Merge

Force merge, allowing unrelated histories:

The fatal: refusing to merge unrelated histories git error can occur when unrelated projects are merged.

git pull origin master --allow-unrelated-histories

Clean

Remove untracked and ignored files:

# Use the '-n' flag for dry run.
git clean -dfx PATH

Remotes

Add a remote:

git remote add private SSH

Change the remote URL:

git remote set-url private SSH

Rename a remote:

git remote rename origin private

Remove a remote:

git remote rm private

Add a remote upstream (e.g. for a fork):

git remote add upstream SSH

Set the default upstream:

git push --set-upstream origin master

Branches

Fetch remotes. This will update the list of remote branches available:

git fetch --all

Check out a remote branch locally:

git checkout -b master origin/master

Rename a branch locally and remotely:

# Rename branch locally.
git branch -m old_branch new_branch

# Delete the old branch.
git push origin :old_branch

# Push the new branch, set local branch to track the new remote.
git push --set-upstream origin new_branch

Delete a local branch:

git branch -D develop

Delete a remote branch:

git push origin --delete develop

Update local branch information:

git remote update origin --prune
git branch --all

Tags

Update tags from a fork:

git push upstream master --tags

Create branch from a tag:

# Go to the starting point of the project.
git checkout origin master

# Fetch all objects.
git fetch origin

# Make the branch from the tag.
git branch new_branch tag_name

# Checkout the branch.
git checkout new_branch

# Push the branch up.
git push origin new_branch

Submodules

Delete a submodule:

git rm -rf PATH

Force remove, when git rm doesn’t work (source):

Can also try git submodule deinit PATH.

Large file storage

Git Large File Storage (LFS) replaces large files (i.e. binary files) with text pointers inside Git, and enables versioned storage of the files on a remote server. This enables offloading of versioned binary data to GitHub or an Amazon S3 bucket, for example. Note that this costs money when used on GitHub.

git lfs track "data/**"

References