rev-parse

It is quite common to get the root directory of the repository with the command:

git rev-parse --show-toplevel

For instance, the above command executed in this repository prints something like as follows:

/xxx/notes

The following shows its usage in a Python script:

#!/usr/bin/env python3

import subprocess

d = (
    subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
    .decode("ascii")
    .strip()  # remove the trailing \n
)
print(d)  # /path/to/notes

It can also be used in bash script:

root_dir=$(git rev-parse --show-toplevel)
echo "root_dir ${root_dir}"

help git-rev-parse outputs helpful information for git rev-parse. In particular, it explains the differences among HEAD~, HEAD~n, HEAD^, and HEAD^n. The following shows the help information about it:


   <rev>^[<n>], e.g. HEAD^, v1.5.1^0
     A suffix ^ to a revision parameter means the first parent of that commit object.  ^<n> means the <n>th parent
     (i.e.  <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when
     <rev> is the object name of a tag object that refers to a commit object.

   <rev>~[<n>], e.g. HEAD~, master~3
     A suffix ~ to a revision parameter means the first parent of that commit object. A suffix ~<n> to a revision
     parameter means the commit object that is the <n>th generation ancestor of the named commit object, following
     only the first parents. I.e.  <rev>~3 is equivalent to <rev>^^^ which is equivalent to <rev>^1^1^1. See below
     for an illustration of the usage of this form.

   G   H   I   J
    \ /     \ /
     D   E   F
      \  |  / \
       \ | /   |
        \|/    |
         B     C
          \   /
           \ /
            A

   A =      = A^0
   B = A^   = A^1     = A~1
   C =      = A^2
   D = A^^  = A^1^1   = A~2
   E = B^2  = A^^2
   F = B^3  = A^^3
   G = A^^^ = A^1^1^1 = A~3
   H = D^2  = B^^2    = A^^^2  = A~2^2
   I = F^   = B^3^    = A^^3^
   J = F^2  = B^3^2   = A^^3^2