dns
+
+
+
sklearn
โ‰ 
elementary
wasm
+
+
matplotlib
yarn
webpack
+
rubymine
!
+
solidity
+
lua
+
+
play
+
+
+
stimulus
+
choo
+
+
+
+
+
+
+
django
+
+
xml
+
+
remix
cobol
+
+
+
+
+
docker
+
quarkus
+
astro
gitlab
jwt
parcel
bash
circle
kotlin
+
+
+
clickhouse
+
php
+
+
zorin
perl
http
dart
+
+
+
sql
+
keras
<-
fauna
+
+
s3
+
+
+
+
+
โˆ‚
0x
Back to Blog
๐Ÿ”ง Setting Up Git Hooks in Alpine Linux: Simple Guide
Alpine Linux Git Version Control

๐Ÿ”ง Setting Up Git Hooks in Alpine Linux: Simple Guide

Published Jun 7, 2025

Easy tutorial on creating and configuring Git hooks in Alpine Linux. Perfect for beginners with step-by-step instructions and practical automation examples.

9 min read
0 views
Table of Contents

๐Ÿ”ง Setting Up Git Hooks in Alpine Linux: Simple Guide

Git hooks help your code stay clean automatically! ๐Ÿ’ป This tutorial shows you how to set up useful Git hooks easily. Donโ€™t worry - itโ€™s simpler than you think! ๐Ÿ˜Š

๐Ÿค” What are Git Hooks?

Git hooks are like automatic helpers that run when you do Git actions. Think of them as smart reminders that check your work!

Git hooks can:

  • ๐Ÿ” Check your code before commits
  • โœ… Run tests automatically
  • ๐Ÿ“ Format your code nicely
  • ๐Ÿš€ Deploy code when you push

๐ŸŽฏ What You Need

Before we start, you need:

  • โœ… Alpine Linux system running
  • โœ… Git installed (apk add git)
  • โœ… A Git repository to work with
  • โœ… Basic knowledge of terminal commands

๐Ÿ“‹ Step 1: Understanding Git Hooks Basics

๐Ÿ” Where Git Hooks Live

Letโ€™s start by looking at where Git stores its hooks. Every Git repo has them! ๐Ÿ˜Š

What weโ€™re doing: Finding the hooks directory in your Git repository.

# Go to your Git repository
cd /path/to/your/repo

# Check if you're in a Git repo
git status

# Look at the hooks directory
ls -la .git/hooks/

# See what hook examples exist
ls -la .git/hooks/*.sample

What this does: ๐Ÿ“– Shows you all the hook examples that Git provides by default.

Expected Output:

-rwxr-xr-x    1 user  user   424 Jun  7 14:00 applypatch-msg.sample
-rwxr-xr-x    1 user  user   896 Jun  7 14:00 commit-msg.sample
-rwxr-xr-x    1 user  user  3327 Jun  7 14:00 pre-commit.sample
-rwxr-xr-x    1 user  user  1348 Jun  7 14:00 pre-push.sample

What this means: Git has prepared example hooks for you to use! โœ…

๐Ÿ’ก Important Tips

Tip: Hook files must be executable and have no file extension! ๐Ÿ’ก

Warning: Hooks with .sample extension donโ€™t run - remove .sample to activate! โš ๏ธ

๐Ÿ› ๏ธ Step 2: Creating Your First Hook

๐Ÿ“ Simple Pre-commit Hook

Now letโ€™s create a useful hook that checks your code before every commit. This prevents mistakes! ๐Ÿ˜Š

What weโ€™re doing: Creating a pre-commit hook that runs basic checks on your code.

# Go to your Git repository
cd /path/to/your/repo

# Create a simple pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
echo "๐Ÿ” Running pre-commit checks..."

# Check for files larger than 1MB
echo "๐Ÿ“Š Checking file sizes..."
large_files=$(find . -type f -size +1M -not -path "./.git/*" 2>/dev/null)
if [ -n "$large_files" ]; then
    echo "โš ๏ธ  Warning: Large files found:"
    echo "$large_files"
    echo "โ“ Continue anyway? (y/n)"
    read answer
    if [ "$answer" != "y" ]; then
        echo "โŒ Commit aborted"
        exit 1
    fi
fi

# Check for TODO comments in staged files
echo "๐Ÿ“ Checking for TODO comments..."
staged_files=$(git diff --cached --name-only)
if [ -n "$staged_files" ]; then
    todos=$(git diff --cached | grep -i "TODO\|FIXME\|XXX" || true)
    if [ -n "$todos" ]; then
        echo "๐Ÿ“‹ TODO comments found in staged changes:"
        echo "$todos"
        echo "๐Ÿ’ก Consider fixing these before committing"
    fi
fi

echo "โœ… Pre-commit checks complete!"
exit 0
EOF

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

# Test the hook
echo "Testing hook..." && git add . && git commit -m "Test commit" --dry-run

Code explanation:

  • #!/bin/sh: Makes it a shell script
  • find . -type f -size +1M: Finds files larger than 1MB
  • git diff --cached: Shows staged changes
  • chmod +x: Makes the file executable
  • exit 1: Stops the commit if thereโ€™s a problem

Expected Output:

๐Ÿ” Running pre-commit checks...
๐Ÿ“Š Checking file sizes...
๐Ÿ“ Checking for TODO comments...
โœ… Pre-commit checks complete!

What this means: Your hook is working and will check every commit! ๐ŸŽ‰

๐ŸŽฎ Letโ€™s Try It!

Time for hands-on practice! This is the fun part! ๐ŸŽฏ

What weโ€™re doing: Creating an advanced pre-commit hook with code formatting and testing.

# Create advanced pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
echo "๐Ÿš€ Advanced Pre-commit Hook"
echo "=========================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored messages
print_status() {
    echo "${GREEN}โœ… $1${NC}"
}

print_warning() {
    echo "${YELLOW}โš ๏ธ  $1${NC}"
}

print_error() {
    echo "${RED}โŒ $1${NC}"
}

echo ""
print_status "Starting pre-commit checks..."

# 1. Check file sizes
echo ""
echo "๐Ÿ“Š Checking file sizes..."
large_files=$(find . -type f -size +1M -not -path "./.git/*" -not -path "./node_modules/*" 2>/dev/null)
if [ -n "$large_files" ]; then
    print_warning "Large files detected:"
    echo "$large_files"
fi

# 2. Check for sensitive information
echo ""
echo "๐Ÿ”’ Checking for sensitive information..."
sensitive_patterns="password|secret|api_key|private_key|token"
if git diff --cached | grep -iE "$sensitive_patterns" >/dev/null; then
    print_error "Potential sensitive information found in staged changes!"
    git diff --cached | grep -iE "$sensitive_patterns" --color=always
    echo ""
    print_error "Please remove sensitive data before committing"
    exit 1
fi

# 3. Check for proper file formatting (if files exist)
echo ""
echo "๐Ÿ“ Checking file formatting..."
staged_files=$(git diff --cached --name-only)

for file in $staged_files; do
    if [ -f "$file" ]; then
        # Check for trailing whitespace
        if grep -q '[[:space:]]$' "$file" 2>/dev/null; then
            print_warning "Trailing whitespace found in: $file"
        fi
        
        # Check for tabs instead of spaces (for certain file types)
        case "$file" in
            *.py|*.js|*.json|*.yaml|*.yml)
                if grep -q $'\t' "$file" 2>/dev/null; then
                    print_warning "Tabs found in: $file (consider using spaces)"
                fi
                ;;
        esac
    fi
done

# 4. Run basic syntax checks
echo ""
echo "๐Ÿ” Running syntax checks..."
for file in $staged_files; do
    if [ -f "$file" ]; then
        case "$file" in
            *.sh)
                if command -v shellcheck >/dev/null 2>&1; then
                    if ! shellcheck "$file" >/dev/null 2>&1; then
                        print_warning "Shell script issues found in: $file"
                        print_warning "Run 'shellcheck $file' for details"
                    fi
                else
                    print_warning "shellcheck not installed - skipping shell script checks"
                fi
                ;;
            *.json)
                if command -v jq >/dev/null 2>&1; then
                    if ! jq empty "$file" >/dev/null 2>&1; then
                        print_error "Invalid JSON syntax in: $file"
                        exit 1
                    fi
                fi
                ;;
        esac
    fi
done

# 5. Check commit message length (for interactive commits)
echo ""
echo "๐Ÿ“ Commit message guidelines:"
print_status "Keep subject line under 50 characters"
print_status "Use present tense ('Add feature' not 'Added feature')"
print_status "Separate subject and body with blank line"

echo ""
print_status "All pre-commit checks passed! ๐ŸŽ‰"
echo ""
EOF

# Make it executable
chmod +x .git/hooks/pre-commit

# Test the advanced hook
echo "# Test file with TODO" > test.txt
echo "TODO: Fix this later" >> test.txt
git add test.txt
git commit -m "Test advanced hook" --dry-run

You should see:

๐Ÿš€ Advanced Pre-commit Hook
==========================

โœ… Starting pre-commit checks...

๐Ÿ“Š Checking file sizes...
๐Ÿ”’ Checking for sensitive information...
๐Ÿ“ Checking file formatting...
๐Ÿ” Running syntax checks...
๐Ÿ“ Commit message guidelines:
โœ… Keep subject line under 50 characters
โœ… All pre-commit checks passed! ๐ŸŽ‰

Awesome work! ๐ŸŒŸ

๐Ÿ“Š Quick Summary Table

Hook TypeWhen It RunsUse For
๐Ÿ”ง pre-commitBefore commitโœ… Code quality checks
๐Ÿ› ๏ธ commit-msgAfter commit messageโœ… Message format validation
๐Ÿ“‹ pre-pushBefore pushโœ… Final tests and builds
๐ŸŽฏ post-commitAfter commitโœ… Notifications and logging

๐Ÿ“จ Step 3: Creating a Commit Message Hook

๐Ÿ“ Enforcing Good Commit Messages

Letโ€™s create a hook that helps you write better commit messages! ๐Ÿ“š

What weโ€™re doing: Making sure all commit messages follow good practices.

# Create commit message hook
cat > .git/hooks/commit-msg << 'EOF'
#!/bin/sh
echo "๐Ÿ“ Checking commit message format..."

commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'

if ! grep -qE "$commit_regex" "$1"; then
    echo ""
    echo "โŒ Invalid commit message format!"
    echo ""
    echo "๐Ÿ“‹ Valid format:"
    echo "   type(scope): description"
    echo ""
    echo "๐Ÿท๏ธ  Valid types:"
    echo "   feat:     New feature"
    echo "   fix:      Bug fix"
    echo "   docs:     Documentation"
    echo "   style:    Code formatting"
    echo "   refactor: Code restructuring"
    echo "   test:     Adding tests"
    echo "   chore:    Maintenance tasks"
    echo ""
    echo "๐Ÿ“ Examples:"
    echo "   feat: add user authentication"
    echo "   fix(api): resolve login timeout issue"
    echo "   docs: update installation guide"
    echo ""
    echo "๐Ÿ’ก Keep description under 50 characters"
    echo ""
    exit 1
fi

echo "โœ… Commit message format is good!"
EOF

# Make it executable
chmod +x .git/hooks/commit-msg

# Test with a good commit message
echo "Test change" > test.txt
git add test.txt
git commit -m "feat: add test functionality"

Code explanation:

  • commit_regex: Pattern for valid commit messages
  • grep -qE: Checks if message matches pattern
  • $1: First argument (the commit message file)
  • Types like feat, fix help organize changes

Expected Output:

๐Ÿ“ Checking commit message format...
โœ… Commit message format is good!

What this does: Ensures all your commits have clear, organized messages! ๐Ÿ“š

๐Ÿš€ Step 4: Creating a Pre-push Hook

๐Ÿงช Running Tests Before Push

What weโ€™re doing: Creating a hook that runs tests before you push code to make sure everything works.

# Create pre-push hook
cat > .git/hooks/pre-push << 'EOF'
#!/bin/sh
echo "๐Ÿš€ Running pre-push checks..."

# Get the remote and URL
remote="$1"
url="$2"

echo "๐Ÿ“ค Pushing to: $remote ($url)"

# Check if we're pushing to main/master branch
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$current_branch" = "main" ] || [ "$current_branch" = "master" ]; then
    echo "โš ๏ธ  Pushing to main branch - running extra checks..."
    
    # Run tests if test directory exists
    if [ -d "tests" ] || [ -f "package.json" ]; then
        echo "๐Ÿงช Running tests..."
        
        # For Node.js projects
        if [ -f "package.json" ]; then
            if npm test >/dev/null 2>&1; then
                echo "โœ… Tests passed!"
            else
                echo "โŒ Tests failed! Push aborted."
                exit 1
            fi
        fi
        
        # For shell script projects
        if [ -d "tests" ]; then
            for test_file in tests/*.sh; do
                if [ -f "$test_file" ]; then
                    echo "   Running $test_file..."
                    if ! sh "$test_file" >/dev/null 2>&1; then
                        echo "โŒ Test failed: $test_file"
                        exit 1
                    fi
                fi
            done
            echo "โœ… All shell tests passed!"
        fi
    fi
    
    # Check for untracked files
    untracked=$(git ls-files --others --exclude-standard)
    if [ -n "$untracked" ]; then
        echo "๐Ÿ“ Untracked files found:"
        echo "$untracked"
        echo "๐Ÿ’ญ Consider adding them or updating .gitignore"
    fi
fi

echo "โœ… Pre-push checks complete! Pushing..."
EOF

# Make it executable
chmod +x .git/hooks/pre-push

echo "โœ… Pre-push hook created!"

What this does: Runs tests and checks before pushing to make sure your code is solid! ๐Ÿ“š

๐ŸŽฎ Practice Time!

Letโ€™s practice what you learned! Try these simple examples:

Example 1: Backup Hook ๐ŸŸข

What weโ€™re doing: Creating a post-commit hook that creates automatic backups.

# Create post-commit backup hook
cat > .git/hooks/post-commit << 'EOF'
#!/bin/sh
echo "๐Ÿ’พ Creating automatic backup..."

# Create backup directory
backup_dir="/tmp/git-backups/$(basename $(pwd))"
mkdir -p "$backup_dir"

# Create backup with timestamp
timestamp=$(date +%Y%m%d_%H%M%S)
backup_file="$backup_dir/backup_$timestamp.tar.gz"

# Create backup (exclude .git directory)
tar -czf "$backup_file" --exclude='.git' .

echo "โœ… Backup created: $backup_file"
EOF

chmod +x .git/hooks/post-commit

What this does: Automatically backs up your project after every commit! ๐ŸŒŸ

Example 2: Notification Hook ๐ŸŸก

What weโ€™re doing: Creating a hook that sends notifications about commits.

# Create notification post-commit hook
cat > .git/hooks/post-commit << 'EOF'
#!/bin/sh
echo "๐Ÿ“จ Sending commit notification..."

# Get commit info
commit_hash=$(git rev-parse HEAD)
commit_message=$(git log -1 --pretty=%B)
author=$(git log -1 --pretty=%an)
timestamp=$(git log -1 --pretty=%cd)

# Log to file
log_file="/tmp/git-commits.log"
echo "[$timestamp] $author: $commit_message ($commit_hash)" >> "$log_file"

# Simple desktop notification (if available)
if command -v notify-send >/dev/null 2>&1; then
    notify-send "Git Commit" "Successfully committed: $commit_message"
fi

echo "โœ… Commit logged and notification sent!"
EOF

chmod +x .git/hooks/post-commit

What this does: Keeps track of all commits and sends notifications! ๐Ÿ“š

๐Ÿšจ Fix Common Problems

Problem 1: Hook not running โŒ

What happened: Git hook doesnโ€™t seem to execute. How to fix it: Check permissions and file naming!

# Check if hook file is executable
ls -la .git/hooks/pre-commit

# Make sure it's executable
chmod +x .git/hooks/pre-commit

# Check if filename is correct (no .sample extension)
mv .git/hooks/pre-commit.sample .git/hooks/pre-commit 2>/dev/null || echo "File already correct"

# Test the hook directly
.git/hooks/pre-commit

Problem 2: Hook blocks all commits โŒ

What happened: Hook prevents you from committing anything. How to fix it: Add bypass option or fix the hook logic!

# Temporarily disable hook
mv .git/hooks/pre-commit .git/hooks/pre-commit.disabled

# Or bypass hooks for emergency commits
git commit --no-verify -m "Emergency commit"

# Fix and re-enable hook
mv .git/hooks/pre-commit.disabled .git/hooks/pre-commit

Donโ€™t worry! Hooks are supposed to help, not block you. Adjust them as needed! ๐Ÿ’ช

๐Ÿ’ก Simple Tips

  1. Start simple ๐Ÿ“… - Begin with basic hooks, add features later
  2. Test thoroughly ๐ŸŒฑ - Make sure hooks work before relying on them
  3. Share with team ๐Ÿค - Put hooks in version control for everyone
  4. Document purpose ๐Ÿ’ช - Add comments explaining what each hook does

โœ… Check Everything Works

Letโ€™s make sure all your hooks are working perfectly:

# Test pre-commit hook
echo "test" > test.txt
git add test.txt
git commit -m "feat: test pre-commit hook" --dry-run

# Check all hooks are executable
ls -la .git/hooks/ | grep -v sample

# Test commit message hook
git commit -m "bad message" --dry-run 2>&1 | grep -q "Invalid" && echo "โœ… Commit message hook works" || echo "โŒ Hook needs fixing"

echo "๐Ÿ”ง Git hooks are ready! โœ…"

Good output:

โœ… Commit message hook works
๐Ÿ”ง Git hooks are ready! โœ…

๐Ÿ† What You Learned

Great job! Now you can:

  • โœ… Create and configure Git hooks
  • โœ… Set up pre-commit code quality checks
  • โœ… Enforce good commit message formats
  • โœ… Run automated tests before pushing

๐ŸŽฏ Whatโ€™s Next?

Now you can try:

  • ๐Ÿ“š Sharing hooks across multiple repositories
  • ๐Ÿ› ๏ธ Creating more advanced testing hooks
  • ๐Ÿค Setting up team-wide hook standards
  • ๐ŸŒŸ Learning about Git hook managers like pre-commit!

Remember: Git hooks automate good practices! Youโ€™re making your development workflow better! ๐ŸŽ‰

Keep practicing and youโ€™ll become a Git automation expert too! ๐Ÿ’ซ