Junior Dev Blog

How to fetch remote git branches and push into them

2023-03-16 at Git category

Pulling Remote Branches in Local Git

To pull remote branches in your local Git repository, follow these steps:

Open your terminal or Git Bash and navigate to your Git repository. Use the git fetch command to fetch all the remote branches from the GitHub repository to your local Git repository.

For example, to fetch all remote branches from the "origin" remote, run:

git fetch origin

On a side note, you can run git remote -v command to list all the origins currently present in your local git repo, remember, whenever we add a remote url, we have to give it a name, we usually give it the name origin but when dealing with multiple remote urls, we can give it different names.

This command will fetch all the remote branches from the "origin" remote.

Once the fetch is completed, you can view all the remote branches using the following command:

git branch -r

This will display a list of all the remote branches in your repository.

To work on a remote branch, you need to create a local branch that tracks the remote branch. Use the git checkout command to create a new local branch and track the remote branch. For example, to create a local branch named local_dev that tracks the remote_dev remote branch, run:

git checkout -b local_dev origin/remote_dev

This command creates a new local branch named local_dev and tracks the remote remote_dev branch. Once you've created the local branch and tracked the remote branch, you can start working on it as you would with any other local branch. Make changes to the codebase, stage and commit changes, and repeat as necessary.

Pushing Changes to Remote Branches

Once you've made changes to a local branch, you can push the changes to the remote branch on GitHub.

Here's how to do it:

Ensure that you're on the local branch that you want to push to the remote branch. For example, to switch to the local_dev branch, run:

git checkout local_dev

Use the git push command to push the changes to the remote branch. For example, to push the changes from the local_dev branch to the remote_dev remote branch, run:

git push origin local_dev:remote_dev

This command pushes the changes from your local local_dev branch to the remote_dev remote branch.

Once you've pushed the changes to the remote branch, other developers can pull the changes into their local Git repository and merge them into their local branches.

Zulfiqar Ali

Personal blog by Zulfiqar Ali.

developer tutorial treats