0
0
Gitdevops~30 mins

pre-push hook in Git - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Git Pre-Push Hook to Run Tests
📖 Scenario: You are working on a team project using Git. To keep the code quality high, you want to run tests automatically before pushing any changes to the remote repository.This will help catch errors early and avoid broken code being shared.
🎯 Goal: Build a Git pre-push hook script that runs a test command before allowing a push.If the tests fail, the push should be stopped.
📋 What You'll Learn
Create a pre-push hook file in the .git/hooks directory
Make the hook file executable
Add a test command inside the hook script
Ensure the push is blocked if tests fail
💡 Why This Matters
🌍 Real World
Pre-push hooks help teams catch errors early by running tests automatically before code is shared.
💼 Career
Knowing how to write Git hooks is useful for DevOps roles and software developers to enforce quality checks.
Progress0 / 4 steps
1
Create the pre-push hook file
Create a file named pre-push inside the .git/hooks directory with the first line #!/bin/sh to specify the shell interpreter.
Git
Need a hint?

The first line of a shell script should be #!/bin/sh to tell Git which shell to use.

2
Add a test command variable
Inside the pre-push file, add a variable named TEST_COMMAND and set it to npm test.
Git
Need a hint?

Use TEST_COMMAND="npm test" to store the test command in a variable.

3
Run the test command and check result
Add code to run the $TEST_COMMAND and check if it succeeds. If it fails, print Tests failed, push aborted. and exit with status 1.
Git
Need a hint?

Use if ! $TEST_COMMAND; then ... fi to run the tests and handle failure.

4
Print success message after tests pass
Add a line to print Tests passed, pushing changes... after the tests succeed.
Git
Need a hint?

Use echo "Tests passed, pushing changes..." to show the success message.