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?
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.
-
6
-
8
-
2@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
– Vince Feb 26 '16 at 5:48
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.
-
12Great 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." – Novice C Sep 28 '17 at 6:28
-
2Source/context for the above quote: git-scm.com/docs/githooks#_description – jmcker Nov 27 '18 at 5:51
-
1In 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.) – Ben Mares Oct 3 '20 at 19:52
You can use the environment variable $GIT_DIR
. $GIT_DIR
points at the .git
directory.
-
How likely is it that
$GIT_DIR/..
will point to the repository root? – David Lord Sep 14 '15 at 4:47 -
It'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. – holygeek Sep 14 '15 at 5:06 -
1Figured. 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? – David Lord Sep 14 '15 at 10:49
-
3
.git
butgit reset --hard
actually creates the working directory structure inside the.git
directory which, in my opinion is an entirely wrong thing to do! – Pavel Šimerda Oct 29 '16 at 22:00