Running git from a git hook
When you want to run the git
command from a git hook, this will
(can?) fail with the message fatal: Not a git repository: '.'
. The
reason is very simple: The GIT_DIR
environment variable is set and
confuses the child git
. You need to unset the GIT_*
variables
before running a child git.
Here’s how you do it in bash:
unset GIT_DIR # possibly others if needed
git status
In Python ≥ 3.5:
env = {k: v
for k,v in os.environ.items()
if not k.startswith("GIT_")}
subprocess.run(["git", "status"], env=env)
In Ruby:
env = ENV.to_hash
env.delete_if { |key, value| key.start_with?("GIT_") }
IO.popen(env, ["git", "status"], :unsetenv_others=>true) { ... }
The :unsetenv_others
is necessary because the default is to add the
environments, which is completely surprising.