WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Git · Intermediate · question 35 of 100

How do you set up a Git hook, and what are some common use cases?

📕 Buy this interview preparation book: 100 Git questions & answers — PDF + EPUB for $5

In Git, a hook is a script that is triggered by a certain Git event, such as committing or pushing changes. Git hooks can be used to automate certain tasks or to enforce rules and policies.

Here’s how to set up a Git hook:

Navigate to the .git/hooks directory in your Git repository.

    cd .git/hooks

Create a new file with the name of the hook you want to create (e.g., pre-commit, post-commit, pre-push, etc.). Make the file executable.

    touch pre-commit
    chmod +x pre-commit

Write the script for the hook. The script should be in Bash or another scripting language supported by your system. For example, a pre-commit hook might look like this:

    #!/bin/bash
    
    # Check for whitespace errors in the files being committed
    git diff-index --check --cached HEAD
    if [ $? != 0 ]; then
    echo "Whitespace errors detected. Please fix them before committing."
    exit 1
    fi

Save the script and exit the file.

    :wq

Now, every time you commit changes to your repository, the pre-commit hook will be executed. In this example, the hook checks for whitespace errors in the files being committed and exits with an error if any are found.

Some common use cases for Git hooks include:

Checking for syntax errors or code style violations before committing changes Running tests before committing changes Preventing certain files or directories from being committed Enforcing commit message formatting or content requirements Sending notifications or performing other actions after certain Git events occur

In summary, Git hooks are scripts that are triggered by certain Git events, such as committing or pushing changes. Git hooks can be used to automate tasks, enforce rules and policies, or perform other actions. To set up a Git hook, create a script in the .git/hooks directory and make it executable. Common use cases for Git hooks include checking for syntax errors, running tests, and enforcing commit message requirements.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Git interview — then scores it.
📞 Practice Git — free 15 min
📕 Buy this interview preparation book: 100 Git questions & answers — PDF + EPUB for $5

All 100 Git questions · All topics