5. Remote Repositories

What is a remote?

A remote in Git is a common repository that all team members use to exchange their changes. In most cases, such a remote repository is stored on a code hosting service like GitHub, GitLab, or Bitbucket or on a private server. While the branches in this repository are used to share changes and collaborate, it's still a local repository that contains the complete commit history of the project.

Adding a remote (git remote add)

To collaborate with others, you need to manage and keep track of the remote repositories you've connected to. The git remote command helps you do this.

  • To add a new remote repository:

    
    git remote add [name-of-remote] [url-of-remote]
    

For example, to add a remote named "origin" that points to a GitHub repository:


git remote add origin <https://github.com/username/repo-name.git>
  • To view a list of existing remotes:

    
    git remote -v
    

Pushing to a remote (git push)

Once you've made your changes and committed them locally, you'll want to send those changes to the remote repository so others can access them or so you have a backup of your latest commits on a remote server. This is done using the git push command.

  • To push changes to a remote:

    
    git push [name-of-remote] [branch-name]
    

For example, to push your local master branch to the origin remote:


git push origin master

Pulling from a remote (git pull)

If other collaborators have pushed changes to the remote repository, you'll want to fetch and merge those changes into your local branch. This is done using the git pull command.

  • To pull changes from a remote:

    
    git pull [name-of-remote] [branch-name]
    

For example, to pull changes from the master branch of the origin remote:


git pull origin master

git pull is essentially a combination of git fetch (which fetches changes from a remote branch without merging them) and git merge (which merges changes from one branch into another).

Cloning a remote repository

If you want to get a copy of an existing Git repository, for instance, a project you'd like to contribute to, the command you need is git clone.

  • To clone a repository:

    
    git clone [url-of-repository]
    

For example, to clone a GitHub repository:


git clone <https://github.com/username/repo-name.git>

This command does a couple of things:

  1. It creates a new directory with the repository's name.

  2. It initializes a new Git repository inside the directory.

  3. It fetches all the data from the remote repository and checks out an editable copy of the most recent version of the project.

Once you've cloned a repository, you can navigate to the directory and start working with the project files.

Last updated