DEV Community

Đặng Đình Sáng
Đặng Đình Sáng

Posted on

Automatically Update the Local Branch with the Remote Version When Switching Branches in Git

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

  1. Go to the .git/hooks directory of the repository of your choice.
  2. Create a file named post-checkout in the .git/hooks directory.
  3. 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
Enter fullscreen mode Exit fullscreen mode
  1. After editing post-checkout, go to the root of the desired repository in a terminal.
  2. Execute the following command in the terminal to give the post-checkout file the permission to execute the script.
chmod +x .git/hooks/post-checkout
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Referenced articles

Top comments (0)