Question: I'm using the script .git/hooks/pre-commit to take snapshots of a MySQL database along with other project files. Here are the contents:

```
#!/bin/bash
mysqldump -u user -ppassword --skip-extended-insert dbname > /path/to/repo/dbname.sql
cd /mnt/hoste/Storage/Code/test-repo/
git add /path/to/repo/dbname.sql

```

If I run:

```
git commit -am "Message"

```

A new dump file is created, but then git tells me:

```
nothing to commit (working directory clean)

```

Then, if I run the identical commit command again, it works:

```
1 file changed, 1 insertion(+), 1 deletion(-)

```

Then, if I run the identical command again, back to "nothing to commit". This pattern continues ad infinitum - works, doesn't work, works, doesn't work. It's not based on time (I've tried commit immediately, and waiting 10 minutes). Mysqldump is certainly updating the .sql file (it date stamps them with hh:mm:ss format near the end of the file).

If I take the script, and run it line by line at the command line (including first cd'ing to the hooks directory to fully simulate running the script), there is a new commit every time. If I put it in an executable file in hooks, or in repo root, and execute it from command line, and then run the commit command, it works every time. It only doesn't work every other time, and then only when it's run from within pre-commit.

What could be causing this weird behaviour?

Answer: 
In a hook, make sure to always specify the git\_dir and work\_tree:

```
git --git-dir=/path/to/your/repo/.git --work-tree=/path/to/your/repo add -- yourFile

```

By changing folder in a hook, you are *not* changing what was the current git repo. If that repo is supposed to change, it is best to reference it explicitly with the `--git-dir` option.
What I observe is that the "pre-commit" hook occurs after git has "frozen" the list of files to be affected (i.e., chosen a content addressable name of the repository state), and it cannot be influenced to alter that; instead, the "git add" in the pre-commit hook is making changes to the index that will be in effect once the commit is finished, and thus the *next* "git commit" shows the result of the "git add" within the pre-commit git hook.

A more comprehensive discussion is here: [Can one re-stage files in a pre-commit git hook?](https://stackoverflow.com/questions/46899526/can-one-re-stage-files-in-a-pre-commit-git-hook)

In my attempts to do "git add" within my own pre-commit hook (I similarly wanted to automatically generate and "git add" some file(s) to my commit), I've tried various tricks with recursive calls to git-commit, but it all ends up being really ugly, and git making un-helpful complaints. I'm going to abandon my hooks/pre-commit attempts, and instead use a shell alias that does "stuff && git add things && git commit".