Skip to content

Git

Git cheat sheet: configuration, aliases, tokens, cloning, branches, commits, tags, submodules, remotes, undoing changes and merge strategies.

8 min readUpdated

Git is a distributed version control system. This note collects the commands needed day to day and the ones that are easy to forget: configuration and aliases, authentication with tokens, branch and tag housekeeping, rewriting and undoing commits, working with forks, and the four common ways to merge a pull request.

Commands use main as the default branch name; replace it if your repository uses another.

Everyday commands

The basic cycle of staging, committing and inspecting changes:

Terminal window
git init # create a new repository in the current directory
git add <path> # stage files
git commit # commit staged files
git diff # show unstaged changes
git diff --cached # show staged changes
git log # show commit history
git merge <branch> # merge a branch into the current one

Configuration

Create an alias

An alias is a shortcut for a long command. This defines git loagd for git log --oneline --all --graph --decorate:

Terminal window
git config --global alias.loagd "log --oneline --all --graph --decorate"

The scope option chooses which config file is written: --global (your user), --system (all users), --local (the repository, the default), --worktree or --file <path>. --blob reads config from a blob and cannot be written to.

List, locate and inspect configuration:

Terminal window
# List all global config
git config --global --list
# Show which file defines a key
git config --show-origin alias.loagd
# Show the value of a key
git config --get alias.loagd

Authenticate with a personal access token

GitHub does not accept account passwords for Git over HTTPS; use a personal access token (PAT) instead. GitLab requires one over HTTPS when two-factor authentication is enabled. Create the token in your account settings (see References), then enter it when Git asks for a password:

Terminal window
$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

A credential helper, or SSH keys instead of HTTPS, saves you from typing the token every time.

Sign off your commits

Some projects require a Signed-off-by: line in each commit message, certifying that you have the right to submit the change (the Developer Certificate of Origin). --signoff (short form -s) adds it using your configured name and email:

Terminal window
git commit --signoff --message "This is my commit message"
git commit -s -m "This is my commit message"

Sign-off is not a cryptographic signature; that is git commit -S with a GPG or SSH key.

Cloning

Clone a specific branch

Terminal window
git clone -b <branch> <remote_repo>

Clone including submodules

Terminal window
git clone --recurse-submodules -j8 <remote_repo>

-j8 fetches up to eight submodules in parallel.

Branches

Git 2.23 added git switch for changing branches; git checkout still works and appears in older documentation. Both forms are shown below.

List branches

Terminal window
git branch # local branches
git branch -a # all branches (local and remote-tracking)

Create a branch

Terminal window
git branch <branch-name> # from the current commit
git branch <branch-name> <sha1-of-commit> # from a specific commit
git switch -c <branch-name> # create and switch
git checkout -b <branch-name> # create and switch (older form)

Switch branches

Terminal window
git switch <branch-name>
git checkout <branch-name>

Push a branch to the remote

Terminal window
git push -u origin <branch-name>

-u sets the remote branch as upstream, so later git push and git pull need no arguments.

Move uncommitted changes to a new branch

Creating a branch keeps the working tree as it is, so uncommitted changes come along to the new branch:

Terminal window
git switch -c <new-branch>
git status

Rename a branch

Terminal window
# Rename the current branch
git branch -m <new-name>
# Rename another branch
git branch -m <old-name> <new-name>
# Delete the old name on the remote and push the new one
git push origin :<old-name> <new-name>
git push origin -u <new-name>

To rename the default branch, do the same, then change the default branch in the GitHub or GitLab project settings before deleting the old name on the remote.

Delete a branch

Terminal window
# Delete locally (refuses if the branch is not merged; -D forces)
git branch -d <branch-name>
# Delete on the remote
git push origin --delete <branch-name>
# or shorter
git push origin :<branch-name>

Prune stale remote-tracking branches

Remove remote-tracking branches (origin/...) whose branch no longer exists on the remote:

Terminal window
# Preview what will be removed
git remote prune origin --dry-run
# Prune
git remote prune origin

Commits

Amend the latest commit message

Terminal window
git commit --amend -m "New message"
git push --force-with-lease origin <branch-name>

The push is only needed if the commit was already pushed. --force-with-lease refuses to overwrite the remote branch if someone else pushed to it in the meantime, unlike plain --force.

Remove an unpushed commit and keep its changes

Terminal window
git reset --soft HEAD~

The commit is removed and its changes stay staged.

Remove a pushed commit

On a shared branch, prefer git revert <commit-hash>: it adds a new commit that undoes the change without rewriting history.

To remove commits from history, find the last commit you want to keep:

Terminal window
git log

Then either force push that commit as the new tip of the remote branch:

Terminal window
git push origin +<commit-hash>:main

or reset the local branch to it and force push:

Terminal window
git reset --hard <commit-hash>
git push --force-with-lease origin <branch-name>

Everyone else working on the branch must then reset their copy:

Terminal window
git fetch
git reset --hard origin/<branch-name>

Check out a specific commit

Terminal window
git switch --detach <commit-hash>
git checkout <commit-hash> # older form
# Or create a branch starting at that commit
git switch -c <new-branch> <commit-hash>

Tags

Rename a tag

Terminal window
git tag <new> <old>
git tag -d <old>
git push origin :refs/tags/<old>
git push origin <new>

git push --tags also works for the last step but pushes every local tag.

Delete a tag

Terminal window
git push origin :refs/tags/<tag-name>
git tag --delete <tag-name>

Submodules

Delete a submodule

Unregister the submodule, which removes its entry from .git/config:

Terminal window
git submodule deinit -f path/to/submodule

Remove its stored repository from .git/modules:

Terminal window
rm -rf .git/modules/path/to/submodule

Remove its entry from .gitmodules and the submodule directory:

Terminal window
git rm -f path/to/submodule

Remotes and forks

View remote URLs

Terminal window
git remote -v

Fetch everything

Fetch all remotes and tags, and prune deleted branches:

Terminal window
git fetch --all --tags --prune

Pull with rebase

Rebase your local commits on top of the latest remote changes instead of creating a merge commit:

Terminal window
git pull --rebase

Fork and pull request workflow

  1. Fork the repository and clone your fork.
  2. Add the original repository as the upstream remote.
  3. Bring your main up to date with upstream.
  4. Create a topic branch, commit, push it to your fork and open a pull request.
Terminal window
git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
git fetch upstream
git switch main
git merge upstream/main
git push origin main
git switch -c ISSUE1
# ... make changes ...
git commit -am "Fix for ISSUE1"
git push -u origin ISSUE1
# Open a pull request from ISSUE1 to upstream main

Repeat the fetch and merge steps to keep the fork in sync later.

Undoing changes

Discard uncommitted changes

git reset --hard discards all staged and unstaged changes to tracked files. git clean -fd deletes untracked files and directories. Neither can be undone.

Terminal window
git reset --hard
git clean -fd

git clean -nd shows what would be deleted without deleting it.

Reset the local branch to match the remote

Save your current state on a branch first, in case you need it again:

Terminal window
git commit -a -m "Saving my work, just in case"
git branch my-saved-work

Then reset:

Terminal window
git fetch origin
git reset --hard origin/main

Merge strategies

A pull request can be integrated in four common ways. They differ in what the history of main looks like afterwards.

Merge commit (git merge --no-ff) always creates a merge commit, even when a fast-forward is possible, so the branch stays visible in the history.

Animation of a merge commit joining a feature branch into the main branch

A typical sequence that commits on development and merges it into main with a merge commit:

Terminal window
git add .
git commit -m "Some message"
git push origin development
git switch main
git pull origin main
git merge --no-ff development
git push origin main
git switch development

Fast-forward merge moves main forward to the branch tip without a new commit. It is only possible when main has no commits that the branch lacks. git merge fast-forwards by default when it can; --ff-only refuses to merge otherwise.

Animation of a fast-forward merge moving the main branch to the tip of the feature branch

Rebase replays the branch’s commits on top of the current main (git rebase main on the branch), giving a linear history. The replayed commits get new hashes.

Animation of a rebase replaying feature commits on top of the main branch

Squash merge (git merge --squash <branch> followed by git commit) combines all changes of the branch into one new commit on main. The individual commits of the branch do not appear in main’s history.

Animation of a squash merge compacting feature commits into a single commit on the main branch

Inspection

View commit history

Terminal window
git log
git log --oneline --all --graph --decorate

Show the current commit hash

Terminal window
git rev-parse --short HEAD
git log --pretty=format:'%h' -n 1

List the 10 largest files

List every file in HEAD with its size, sort by size and show the last ten:

Terminal window
git ls-tree -r -t -l --full-name HEAD | sort -n -k 4 | tail -n 10

References

Related notes

2 min read

ngrok

Expose a local web server on a public HTTPS address with ngrok, for webhook testing, demos and testing on real devices.

  • Developer Tools
2 min read

NetBeans

Build Apache NetBeans from source, clear the Recent Projects list and choose the JDK the IDE runs on.

  • Developer Tools
3 min read

Vim and Neovim

Set up Vim with VimTeX and Zathura for LaTeX on macOS, and add the Neo-tree file explorer to Neovim.

  • Developer Tools

Type to search the whole site.