CodeBlanks Logo Icon CodeBlanks

pre-receive

Learn the server-side pre-receive hook.

What Is the pre-receive Hook?

`pre-receive` is a server-side hook that runs before a push operation is accepted. It can inspect reference updates sent to the server. If the script exits with a non-zero status, the push is rejected.
#!/bin/bash
echo "Checking push"

Push Checks and Input Data

The `pre-receive` hook reads the old object ID, the new object ID, and the reference name for each update from standard input. These values can be used to enforce policies on incoming branches or tags.
while read old new ref
do
  echo "$ref"
done

Practice Reject Pushes to the Main Branch

Write a `pre-receive` script. Read input lines into the `old`, `new`, and `ref` variables. Reject the push if the reference is `refs/heads/main`. Otherwise, print that the check is complete.

Starter code

terminal
# Girdi satırlarını oku
# Referansı denetle

Sample solution

terminal
#!/bin/bash
while read old new ref
do
  if [[ "$ref" == "refs/heads/main" ]]; then
    echo "Ana dala push yasak" >&2
    exit 1
  fi
done
echo "Push kontrol edildi"

Expected output

Push kontrol edildi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does the pre-receive hook run?

  • When a repository is cloned
  • When commit history is displayed
  • When a local file is saved
  • Before the push is accepted by the server Correct answer

Explanation: `pre-receive` runs to determine whether an incoming push request should be accepted.

2 Read pre-receive Input

Question
while read old new ref
do
  echo "$_____"
done____
Answer
while read old new ref
do
  echo "$_____"
doneref

Explanation: The `ref` variable contains the name of the reference being updated.

3 Match the pre-receive Concepts

Term Meaning
pre-receive Runs before a push is accepted
Standart girdi Carries update information
Sunucu tarafı Runs on the remote repository
Sıfır dışı çıkış kodu Rejects the push operation

All lessons in Expert