An example of Git pre-push hook

An example of Git pre-push hook

Git hooks are actually bash scripts that would be triggered by certain actions. A pre-push hook is triggered before a push action.

The hook below will check there is any New or Modified java files in the repository before the push happens. If yes, it will abort the push and give you an warning.

Code:

  #!/bin/sh
if git ls-files -o -m --exclude-standard --exclude=special-file.java | grep  "java$"> /dev/null
  then
      echo "---------------------------------------------------";
      echo "There are uncommited NEW or MODIFIED java files !"
            echo "---------------------------------------------------";
      exit 1;
fi

-m shows tracked but modified files; -o shows untracked files; --exclude-standard means not showing the files that have already been excluded git config files (like .gitignore). You can also exclude your "secret" files using -exclude;

From git ls-files --help:

-m, --modified
       Show modified files in the output
-o, --others
       Show other (i.e. untracked) files in the output
--exclude-standard
       Add the standard git exclusions: .git/info/exclude, .gitignore in
       each directory, and the user’s global exclusion file.

Install pre-push hook

Git hooks need to be put under .git/hooks folder with certain names. But typically this folder will not be tracked by git. So if you want to keep track of you pre-push hook history, you can put the hook file somewhere else and then create a symbol link to it.

cd .git/hooks
ln -s /what/ever/the/path/pre-hook.sh pre-hook.sh

Comments !