Git Demystified

June 18, 2019

Distance from HEAD

There are several ways to refer to a previous commit from HEAD.

  • HEAD~ - refers to the first parent.

    • HEAD~2 - first parent’s first parent.
    • HEAD~~ - alternative form.
  • HEAD^ - same as above.

    • HEAD^2 - second parent (for merges).
  • HEAD@{1} - same as above.

    • HEAD@{2} - parent’s parent.

Files (Staging Area)

Unintuitively, the git reset command is used for refs and files

  • git add «file» - stage for commit.

    • git add -A - new, modified, and deleted files.
    • git add -u - modified and deleted files (new files are ignored).
    • git add . - new and modified (deleted files are ignored).
  • git reset «file» - unstage. Think of it as the opposite to git add.
  • git reset --hard - equivalent to git reset . ; git checkout ..

checkout vs. reset

git reset moves both the HEAD and branch pointer. git checkout only moves the HEAD, detaching it.

To reattach a detached HEAD,

$ git checkout «branch»   # e.g., git checkout master

To undo an accidental git reset,

$ git reflog
$ git reset «hash»

Alias

The config files to set aliases are found in ~/.gitconfig. You can create a section in the file as follows:

[alias]
ac = !git add -A && git commit -m
c = commit
co = checkout
l = log --all --decorate --oneline --graph
s = status
sh = stash

An alias expansion can be prefixed with an exclamation mark ! to treat it as a shell command.


Profile picture

Written by Samuel Moon who lives and works in Los Angeles building useful things. Check out my GitHub.