11

I'm trying to add a pre-commit script.

The script works, but Git ignores the changes to the file. It seems like Git ignores any changes I make in .git, but it isn't specified in .gitignore.

For example:

# Add a hook that runs Hello, World!
echo "#\!/bin/sh \n echo 'Hello, World!'" > .git/hooks/pre-commit

# Make the hook runnable
chmod +x .git/hooks/pre-commit

# Check changes
git status

# > Your branch is up to date with 'origin/master'.
# > nothing to commit, working tree clean

Therefore, how do I commit my hook to the repository?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Liron Navon
  • 1,068
  • 1
  • 11
  • 22

2 Answers2

24

I found it -

Create a directory in the project root, let's call it git_hooks. Add the script to it, and set the directory as the Git hooks target using git config.

# Create directory
mkdir git_hooks

# Add a hook that runs Hello, World!
echo "#\!/bin/sh \n echo 'Hello, World!'" > git_hooks/pre-commit

# Make the hook runnable
chmod +x git_hooks/pre-commit

# Configure git to use the new hook - it will stay with the repository
git config core.hooksPath "./git_hooks"

# The script will run on every commit:
git commit -am "added pre-commit hook"
> Hello, World!
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Liron Navon
  • 1,068
  • 1
  • 11
  • 22
2

The .git repository isn't part of the repository. It is the repository.

If you want to save the configuration of your repository, I suggest you use another Git repository for that purpose.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • 4
    So how do I add a hook? do I have to add another directory and force symlink it? what is the proper way to add a hook? this is what every tutorial shows me unless I use some fancy framework like python pre-commit, or js husky? – Liron Navon Aug 21 '19 at 12:46