Why doesn't setting GIT_WORK_TREE work in a post-commit hook?

I’m trying to use the following post-commit hook to deploy to a particular directory after each successful commit:

#!/bin/sh
export GIT_WORK_TREE=/var/www/example/
export GIT_DIR=/home/mark/test/.git/
git checkout -f

However, after committing I get the following error:

$ git commit -m 'An example commit.'
fatal: Unable to create '/var/www/example/.git/index.lock': No such file or directory
[master 0938e48] An example commit.

… as if the GIT_WORK_TREE setting is being ignored. Why does setting this environment variable appear to be not working? I’m using git version 1.7.4.1.

  • Git: how to merge a commit into a branch via an update githook
  • How to execute commands after post-receive hook
  • How to add git hook for sending commit messages into pivotal tracker story as comments?
  • Commit in git only if tests pass
  • Pre-commit hook for devtools::document
  • Putting git hooks into repository
  • TortoiseGit - No option for Post-Commit Hook in the Settings
  • Git hook to reject a push containing a submodule update?
  • One Solution collect form web for “Why doesn't setting GIT_WORK_TREE work in a post-commit hook?”

    The problem here is that in post-commit hooks (and also
    pre-commit, prepare-commit-msg and commit-msgt) the
    GIT_INDEX_FILE environment variable is set to .git/index. (This
    isn’t documented in the githooks
    documentation, but I’ve
    posted elsewhere about the settings of environment variables and the
    current directory in git
    hooks.)

    The effect of the GIT_INDEX_FILE environment variable is described
    in the ENVIRONMENT VARIABLES section of the git man page as:

    GIT_INDEX_FILE

    This environment [variable] allows the specification of an alternate index file. If not specified, the default of $GIT_DIR/index is used.

    … and for some reason, in this situation, GIT_INDEX_FILE is being
    used relative to GIT_WORK_TREE.

    To make the hook work as you would expect, you just need to unset
    GIT_INDEX_FILE, so your hook would look like:

     #!/bin/sh
     unset GIT_INDEX_FILE
     export GIT_WORK_TREE=/var/www/example/
     export GIT_DIR=/home/mark/test/.git/
     git checkout -f
    
    Git Baby is a git and github fan, let's start git clone.