TechEarl

Git Hooks: Native Scripts, Husky, and lint-staged

Write and share Git hooks, handle staged files with lint-staged, understand core.hooksPath, Husky, bypasses and troubleshooting, then push-to-deploy with a post-receive hook or GitHub Actions.

Ishan KarunaratnePublished ⏱️ 13 min readUpdated
Share thisCopied
Create a pre-commit hook, share hooks with core.hooksPath, Husky and lint-staged, and push-to-deploy with a post-receive hook or GitHub Actions.

A Git hook is a local executable that Git runs at a named event. For a basic repository using the default hooks directory, save this as .git/hooks/pre-commit:

bash
#!/bin/sh
# Check the project before committing.
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained
npm run lint

Then enable it:

bash
chmod +x .git/hooks/pre-commit

This assumes the project already has a working lint script and installed dependencies. A nonzero result blocks the commit. It checks the working tree according to that script, not an isolated copy of exactly what is staged. For staged-file handling, use the lint-staged example below.

This page covers the local hooks (pre-commit, commit-msg, pre-push), sharing them with core.hooksPath or Husky, lint-staged, and bypassing and troubleshooting. On the server side, it covers push-to-deploy with a post-receive hook and the GitHub Actions alternative.

What is a Git hook?

Git recognizes specific filenames such as pre-commit, commit-msg and pre-push. A file named pre-commit.sample is only a sample; remove the suffix and make it executable to activate it. The interpreter comes from the shebang, so shell, Python and Node hooks all need their runtime installed where Git runs.

The default location is $GIT_DIR/hooks. In an ordinary checkout that is .git/hooks, but linked worktrees, bare repositories and core.hooksPath can change the layout. Check a configured override with:

bash
git config --show-origin --get core.hooksPath

No output normally means no override is configured. Do not assume .git is always a directory; worktrees can use a .git file pointing to metadata elsewhere.

Common hooks and when they run

HookWhen it runsTypical use
pre-commitBefore recording the commitFast checks or a linter
prepare-commit-msgBefore the commit-message editorPopulate a ticket or template
commit-msgWith the proposed message fileValidate message format
post-commitAfter the commitLocal notifications
pre-pushBefore transferring the pushTests or an accidental-push check
post-checkoutAfter a checkout or branch switchRefresh local derived files
post-mergeAfter a successful mergeReport dependency changes

Blocking behavior belongs to each hook's documented contract. pre-commit, commit-msg and pre-push can reject their operation with a nonzero exit status. A post-commit notification cannot undo the commit that already happened.

Server-side hooks are a different enforcement point. See pre-receive hook declined for rejected pushes, and deploy with a post-receive hook below for push-to-deploy on your own server.

A pre-commit hook with useful failure output

A little output makes failures easier to diagnose:

bash
#!/bin/sh
# Run the repository lint script before a commit.
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained

te_log() {
  printf '[pre-commit] %s\n' "$1"
}

te_log 'running npm run lint'
if ! npm run lint; then
  te_log 'lint failed; commit aborted'
  exit 1
fi
te_log 'lint passed'

For example, a configured linter could report:

text
[pre-commit] running npm run lint
src/login.js: an unused variable failed the lint check
[pre-commit] lint failed; commit aborted

The exact linter output depends on its configuration. Fix the error, stage the intended fix and retry. Git has not created a commit when pre-commit rejects it. An unstaged change can also cause this full-working-tree check to fail, even when the staged change is valid.

Share native hooks with core.hooksPath

Files inside .git/hooks do not travel with a clone. To review and version the scripts, move them into a tracked directory:

bash
mkdir -p .githooks
mv .git/hooks/pre-commit .githooks/pre-commit
chmod +x .githooks/pre-commit
git config --local core.hooksPath .githooks
git add .githooks/pre-commit

Commit the tracked file through the normal project workflow. Each new clone still needs the local activation step:

bash
git config --local core.hooksPath .githooks

Inspect the scripts before enabling them. A tracked hook executes code from the repository, including future updates to that hook; cloning alone deliberately does not activate arbitrary repository scripts. A setup script can make activation convenient without hiding this trust decision.

Choose one owner for core.hooksPath. A native .githooks setup and Husky should not compete to configure the same clone.

Share hooks with Husky

For an npm-based project, the current Husky setup is:

bash
npm install --save-dev husky
npx husky init

init adds a prepare script and creates .husky/pre-commit. Edit that file to contain the command you want:

bash
npm run lint

Commit the project configuration, lockfile and .husky/pre-commit. Husky's current generated launchers live in .husky/_, and it points core.hooksPath there; the editable hook remains in .husky/pre-commit. Do not manually point Git at the wrong directory or copy old Husky bootstrap lines into a current installation.

Installation needs its lifecycle script to run with Git available. A clone with scripts disabled, development dependencies omitted or HUSKY=0 is not automatically protected. Treat the local hook as useful feedback and keep required checks in CI.

Lint only the staged changes with lint-staged

A pipeline that extracts filenames from git diff and sends them to xargs is easy to get wrong. It can split paths with spaces, omit renames, or lint unstaged content in a partially staged file. I use lint-staged for that workflow:

bash
npm install --save-dev lint-staged

Merge this key into package.json; the relevant ESLint and Prettier dependencies and configuration must already exist:

json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": "eslint --fix",
    "*.{css,md}": "prettier --write"
  }
}

Change .husky/pre-commit to:

bash
npx lint-staged

By default, lint-staged creates a backup stash and hides unstaged changes in partially staged files while tasks run, then restores them. Successful task changes are included in the commit. Those safeguards are configurable, so do not disable them casually. Test the setup with a filename containing spaces and with a partially staged file; review the resulting diff when a formatter changes code.

Lint-staged runs commands on matching paths. It is not a substitute for a full build or test suite that depends on the whole project.

Bypassing and disabling hooks

bash
git commit --no-verify -m "Describe the change"
git push --no-verify

For git commit, --no-verify skips pre-commit and commit-msg; it does not skip prepare-commit-msg. For a push, it skips pre-push. A user can also change or remove their local hooks, so they are not a security boundary. Required CI checks and protected-branch policy provide enforcement at the shared repository.

To disable a raw hook temporarily:

bash
chmod -x .git/hooks/pre-commit

For a custom hooks path, use the actual configured file. To remove a custom configuration after uninstalling the tool that owns it:

bash
git config --local --unset core.hooksPath

That returns this clone to its default path unless a higher-level Git configuration supplies another value.

Why a hook does not run

Check the filename, executable permission, shebang and current core.hooksPath. Also check whether the event really occurred: an editor opening is not evidence of a completed commit, and an interrupted merge is not a successful post-merge event.

A GUI Git client can have a different PATH from your interactive shell, especially when Node comes from a version manager. Run the command under the same environment and check the tool's own troubleshooting instructions. On Windows, preserve LF line endings in shell hooks. Non-executable hooks may produce Git advice rather than a hard error.

Deploy with a post-receive hook

Hooks also run on the server side, and the most useful one there is post-receive: Git runs it right after a push lands. Pair it with a bare repository on your own server and git push production main becomes your deploy command, with no CI vendor and no SSH-in-and-pull dance.

Why the server repo is bare

A normal repository has a working directory, and you cannot safely push to a branch that is checked out in it, because the working tree and the branch pointer would disagree. A bare repository has no working directory, just the objects, refs and hooks, which is exactly what a remote should be. The hook then materializes the files somewhere else. So the server has two directories:

  • A bare repo that receives pushes, e.g. /srv/git/myapp.git
  • The live deploy target, e.g. /var/www/myapp

On the server (once ssh user@host works; if it throws Permission denied (publickey), see the Permission denied (publickey) fix first):

bash
mkdir -p /srv/git/myapp.git
cd /srv/git/myapp.git
git init --bare
mkdir -p /var/www/myapp

git init --bare puts hooks/, objects/ and refs/ directly in myapp.git/ rather than inside a .git subfolder. That is correct.

The post-receive script

bash
cat > /srv/git/myapp.git/hooks/post-receive <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

# Deploy hook for myapp
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained

WORK_TREE="/var/www/myapp"
GIT_DIR="/srv/git/myapp.git"
DEPLOY_BRANCH="main"

te_log() {
  echo "[deploy] $1"
}

te_deploy() {
  local ref="$1"
  local branch="${ref##refs/heads/}"

  if [ "$branch" != "$DEPLOY_BRANCH" ]; then
    te_log "skipping $branch (only $DEPLOY_BRANCH deploys)"
    return 0
  fi

  te_log "deploying $branch to $WORK_TREE"
  git --work-tree="$WORK_TREE" --git-dir="$GIT_DIR" checkout -f "$branch"
  te_log "done"
}

while read -r oldrev newrev ref; do
  te_deploy "$ref"
done
EOF
chmod +x /srv/git/myapp.git/hooks/post-receive
  • set -euo pipefail stops the hook at the first failing command and prints the error back to the pusher. It cannot reject the push: post-receive runs after Git has already updated the refs, so the push succeeds either way. To refuse a push, use a pre-receive hook; to avoid a half-deployed site, build somewhere separate and switch over only on success (see the build step below).
  • post-receive receives one line per pushed ref on stdin, formatted oldrev newrev refname, which is why the ref is read in a while read loop rather than from an argument.
  • The branch filter means pushing a feature branch does nothing; only main deploys. Since main is the branch that ships, protect it on the origin so nothing lands there without review.
  • git --work-tree=... --git-dir=... checkout -f forces /var/www/myapp to match the pushed branch. -f discards hand-edits in the work tree, which is what you want: the repo is the source of truth.

Back on your local machine, add the server as a remote and push:

bash
git remote add production user@your-server.com:/srv/git/myapp.git
git push production main

Your [deploy] log lines stream back over SSH, and /var/www/myapp holds the latest code. checkout -f writes exactly what Git tracks, so a file you never committed, or one in your .gitignore, never reaches the server. Either commit it (never secrets) or provision it on the server separately, and keep the bare repo out of any web-served path.

Add a build step

For a static site or a compiled app, build between the checkout and "done". With set -e on, a failing build stops the hook before "done" (the push itself has already been accepted):

bash
te_deploy() {
  local ref="$1"
  local branch="${ref##refs/heads/}"
  [ "$branch" != "$DEPLOY_BRANCH" ] && return 0

  te_log "deploying $branch"
  git --work-tree="$WORK_TREE" --git-dir="$GIT_DIR" checkout -f "$branch"

  cd "$WORK_TREE"
  npm ci
  npm run build
  npm prune --omit=dev
  te_log "done"
}

npm ci installs the full dependency set because build tools usually live in devDependencies; npm prune --omit=dev strips them back out after the build. One honest limit: if the build fails, the working tree is already updated but the build is stale. For anything beyond a trivial site, deploy into a fresh directory and swap a symlink only after the build succeeds.

When the deploy hook does not fire

  • The hook does not run. The file must be hooks/post-receive exactly (no .sh, no .sample) and executable. Check the x bits with ls -l hooks/post-receive.
  • Wrong shell. The shebang must point at a real shell on the server; some minimal images only have /bin/sh.
  • Permission denied writing the work tree. The SSH user that receives the push must be able to write /var/www/myapp. A mismatch between the git user and the web user is the classic failure.
  • The push succeeds but nothing deploys. The DEPLOY_BRANCH filter is probably rejecting the branch you pushed. Add a te_log "got $branch" line to see what the hook receives.

Push-to-deploy with GitHub Actions

The other deploy style moves the work off your server: with GitHub Actions, a YAML file in .github/workflows/ tells GitHub to build, test and deploy on every push to main. A workflow has three nested parts: an event triggers it (a push, a pull request, a schedule, a manual click), a job runs on one fresh runner machine, and steps run top to bottom inside the job. Here is a workflow for a Node.js project on a server you can reach over SSH, saved as .github/workflows/deploy.yml. The runner tests and builds the commit; the server then checks out that exact commit and builds it itself, so what ships is the code that passed:

yaml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the code
        uses: actions/checkout@v4

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 26

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build
        run: npm run build

      - name: Deploy over SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.DEPLOY_HOST }}
          username: ${{ secrets.DEPLOY_USER }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          script: |
            set -e
            cd /var/www/myapp
            git fetch origin main
            git checkout --detach ${{ github.sha }}
            npm ci
            npm run build
            npm prune --omit=dev
            pm2 restart myapp
  • on: push: branches: [main] is the trigger; pushes to other branches do not deploy.
  • actions/checkout@v4 clones the repo onto the runner, which is otherwise an empty machine; actions/setup-node@v4 installs the Node version you ask for.
  • If npm test or npm run build fails, the job stops and the deploy step never runs. That ordering is the safety net.
  • The deploy step SSHes into the server, checks out the exact commit the runner tested (github.sha), builds it there and restarts. The runner's build output stays on the runner; it is a gate, not the artifact that ships. If you would rather ship the runner's build, upload it as an artifact or copy it with rsync/scp in the deploy step instead of rebuilding. Keep the server's checkout clean and let the workflow own it, or the checkout can fail on a file someone edited in place.

For the Node setup half in more depth (caching, matrix builds), see setting up Node in a GitHub Actions workflow. If you want to prove the pipeline before wiring a server, start with just the checkout, setup-node, npm ci and npm test steps, break a test on purpose, and watch the red X appear in the Actions tab.

Keep secrets out of the YAML

The deploy step never contains a password or key; it reads secrets.DEPLOY_SSH_KEY and friends from the repo's encrypted secret store. The workflow file is committed, so anything written in it is visible to anyone who can read the code and stays in history. Add secrets under Settings, Secrets and variables, Actions, New repository secret. The runner can read them at run time, nobody can read them back out of the UI, and GitHub masks them in logs. I use one secret per credential and a deploy-only SSH key (public half in the server's authorized_keys, private half in the secret), never my personal key. If a credential ever lands in a commit, rotate it and scrub it from history.

Push-to-deploy also makes main load-bearing: whatever lands there ships. Route changes through pull requests, let CI run on the PR, and merge only when it is green.

post-receive hook vs GitHub Actions

post-receive hookGitHub Actions
Where deploy runsOn your server, triggered by your pushOn the vendor's runners, triggered by a push to GitHub
DependenciesSSH access to the box, a bare repoA GitHub repo, a workflow file, and (for this recipe) SSH access from the runner
Build stepYou run it in the hook (or skip it)Runs on the runner before deploy
Cost / vendorNone beyond your serverFree tier, then metered
Secrets handlingServer env / files you manageEncrypted repo secrets
Best forA single VPS you control, simple sitesMulti-step pipelines, tests-then-deploy, teams

Neither is better in general. The hook is the leanest thing that works for one server; Actions is the right call when tests should gate the deploy or you want the pipeline to live with the code. Both recipes here need SSH to the server; for a target without SSH (a PaaS, object storage, a container registry), swap the deploy step for that platform's own deploy action.

FAQ

The default local hooks are not. Track scripts in a separate directory and opt in with core.hooksPath, or use a reviewed package-manager setup such as Husky.

Only if its commands are designed to do that. A plain npm run lint normally checks working-tree files. lint-staged handles selected files and, by default, hides unstaged changes in partially staged files while its tasks run.

Yes. Local hooks provide feedback, while required server or CI checks enforce shared policy. The --no-verify flag skips specific hooks, not every hook event.

Pulling on the server means logging in, navigating to the directory and remembering to pull every time. A post-receive hook removes those steps: one git push from your machine both uploads the code and runs the deploy.

Use a post-receive hook for a single server you have SSH access to and a simple deploy. Use GitHub Actions when you want tests to gate the deploy or a multi-step build. The SSH-based Actions recipe still needs SSH to the server; for a host without SSH, use that platform's deploy action instead. The hook is leaner; Actions is more capable.

The job stops at the failing step. Because the deploy step comes after the test and build steps, nothing reaches your server.

See also

Sources

Authoritative references this article was fact-checked against.

TagsGit HooksGitVersion Controlpre-commithuskyDevOpspost-receiveGitHub ActionsDeployment

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

List the files changed in git from the command line: working tree, staged, last commit, between two branches, and piping the list to a linter to check only what changed.

How to List the Files Changed in Git

List the files changed in git: working tree, staged, the last commit, between branches, or since N commits. Then pipe the list straight into a linter so you only check what changed.

Learn Git from scratch: install, identity setup, the staging area, your first commit, pushing to GitHub, fixing the first errors beginners hit, and putting a WordPress site under Git.

Git for Beginners: How to Actually Get Started

A practical, no-jargon introduction to Git: the mental model, installing it, setting your identity, the staging area, your first commit, pushing to GitHub, the first errors you will hit, time-saving Git aliases, and using Git with WordPress.