Skip to content

Find the git work-tree root

Print the top-level directory of a git repo, or an error if the path is not a repo.

18th August 2026

get_git_root() {
  local root
  local retval

  (
    if [[ -n $1 ]]; then
      if [[ ! -d $1 ]]; then
        echo "$1 is not a valid directory"
        return 1
      fi
      cd "${1}" || return 1
    fi

    if git rev-parse --is-inside-git-dir > /dev/null 2>&1; then
      while [[ $(git rev-parse --is-inside-git-dir) == true ]]; do
        cd ..
      done
    fi

    if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
      root=$(git rev-parse --show-toplevel)
      retval=0
    else
      root="${PWD} is not a git repo"
      retval=1
    fi

    echo "${root}"
    return $retval
  )
}