Pre-commit Security Hooks with Shell Scripting
The commit is about to land. You’ve reviewed the code, but there’s one last check before it can touch the main branch—your shell-scripted pre-commit security hook.
Pre-commit security hooks are the first line of defense against pushing risky code. They run locally, intercept a commit, and inspect files for vulnerabilities before they ever reach your repo. A well-written shell script can catch secrets, unsafe configs, outdated dependencies, and insecure patterns instantly.
Why use shell scripting for pre-commit hooks
Shell scripts are fast, portable, and work anywhere Git runs. They don’t depend on extra runtimes. You control exactly what runs and when. Common security checks to build into your hooks include:
- Secret detection via regex or entropy scanning
- Unsafe function or API calls in source files
- Configuration file sanity checks
- Dependency validation against a CVE feed
How to set it up
- Create an executable shell script in
.git/hooks/pre-commit. - Add your security checks, exiting with a non-zero status if risks are found.
- Keep it efficient—slow hooks damage workflow discipline.
- Use clear output messages so failures are actionable.
Example minimal pre-commit security hook in shell:
#!/bin/sh
# Secret scan for AWS keys
if grep -E 'AKIA[0-9A-Z]{16}' $(git diff --cached --name-only); then
echo "Potential AWS secret detected. Commit aborted."
exit 1
fi
# Basic unsafe function check
if grep -E 'system\(' $(git diff --cached --name-only); then
echo "Unsafe system() call found. Commit aborted."
exit 1
fi
exit 0
Best practices
- Keep hooks under 1–2 seconds execution time
- Version-control your hooks; share them via template repos or automation
- Regularly update rules to match the latest security advisories
- Avoid false positives—tune patterns carefully
Pre-commit security hooks with shell scripting give you immediate, localized control over what enters your codebase. They’re simple yet powerful. Start small, then expand coverage as threats evolve.
You can skip manual setup entirely with modern tools. Deploy robust, zero-config pre-commit security checks now—see it live in minutes at hoop.dev.