In a git hook is the current working directory guaranteed to be within the git repository?
Solution 1
It is based on the value set for environment variable GIT_DIR
. It is set to the root of the repository when the hook starts running. Many hooks, especially those doing a pull from another repo, unset ( and reset) this environment variable as needed.
Solution 2
The current answers appear to be outdated. As of 2.9.0, the docs state the following:
Before Git invokes a hook, it changes its working directory to either the root of the working tree in a non-bare repository, or to the $GIT_DIR in a bare repository.
https://git-scm.com/docs/githooks/2.9.0
Solution 3
You can use the environment variable $GIT_DIR
. $GIT_DIR
points at the .git
directory.
Dickon Reed
Updated on June 21, 2020Comments
-
Dickon Reed almost 4 years
Experimentally it seems that git hooks get run with the current directory set to be the root of the repository. However, I can't see any guarantee about that in the git documentation. Should I rely on the current working directory to locate the git repository, or is there a better way to work out the git repository associated with the hook?
-
PuercoPop about 12 yearsDoes $GIT_DIR has a trailing slash ?
-
David Lord over 8 yearsHow likely is it that
$GIT_DIR/..
will point to the repository root? -
holygeek over 8 yearsIt's not foolproof. Don't use
$GIT_DIR/..
. That will break when the repo is a bare repo. A bare repo has no working directory hence no "repository root". Also it will break when .git is a link instead. -
David Lord over 8 yearsFigured. Any way to get the repo root under normal usage? For a pre-commit hook which uses the repo as configuration files for a program, for instance?
-
Ghopper21 over 8 yearsThis is NOT a correct answer. GIT_DIR is NOT always set to the root of the repo. See this blog.
-
Ghopper21 over 8 yearsThis is NOT correct in all cases. See this blog.
-
Vince about 8 years@Ghopper21 That article isn't entirely correct either. It says that for the post-commit hook, the current directory is the top level of the working tree. However, my very simple post-commit script didn't find other scripts at the top level of the working tree. e.g.:
.git/hooks/post-commit: 1: .git/hooks/post-commit: post-commit_push_gitweb.sh: not found
-
Novice C over 6 yearsGreat answer. A clarification was made in later revisions (2.13.0). "An exception are hooks triggered during a push (pre-receive, update, post-receive, post-update, push-to-checkout) which are always executed in $GIT_DIR."
-
jmcker over 5 yearsSource/context for the above quote: git-scm.com/docs/githooks#_description
-
Ben Mares over 3 yearsIn plain language: it's the top-level directory of your repository. ("Bare" essentially refers to a repository consisting of only the
.git
directory, and with no files checked out.)