When you switch to your main branch during development, do you ever forget to perform a git pull?
When you checkout to a particular branch, you can utilize a feature called "Git Hooks" to have a git pull executed automatically.
This article explains how to configure it.
Setup procedure
- Go to the
.git/hooksdirectory of the repository of your choice. - Create a file named
post-checkoutin the.git/hooksdirectory. - In this
post-checkout, write the following code:
#! /bin/sh
# Get the current branch name
branch=$(git rev-parse --abbrev-ref HEAD)
# Do a git pull when you move to the `master` branch
if [ "$branch" = "master" ]; then
git pull origin $branch
fi
- After editing
post-checkout, go to the root of the desired repository in a terminal. - Execute the following command in the terminal to give the
post-checkoutfile the permission to execute the script.
chmod +x .git/hooks/post-checkout
This completes the configuration. The post-checkout file above will automatically perform a git pull when you git checkout (or git switch) from any branch to the master branch.
If you want to set up "automatic local modernization on branch move" for multiple branches
#!/bin/sh
# Get the current branch name
branch=$(git rev-parse --abbrev-ref HEAD)
# Handle the 'master' and 'develop' branches
if [ "$branch" = "master" ] || [ "$branch" = "develop" ]; then
# Calling exec < /dev/tty assigns standard input to the keyboard
exec < /dev/tty
read -n 1 -p "Do you want to pull the '$branch' branch? (y/n): " answer
echo "\n"
if [ "$answer" = "y" ]; then
# Break line
git pull origin $branch
else
echo "Skipping 'git pull' for the '$branch' branch."
fi
# Handle other branches
else
echo "Skipping 'git pull' for the '$branch' branch."
fi
Top comments (0)