Git: Pull changes from a local repository

This may a bit of niche problem to have, to pull changes from one clone of a repository to another clone, on the same machine. Why would I need to do this?

The why

At work, I have multiple of the same repository locally on my machine. One 'main' clone and multiple clones of the repository as submodules in another repository. I work on these local clones in different contexts, and I don't always know or realize I need to use it in a different context later.

If I start work in the main repository, then want to test it as part of one of the test setups, what do I do? Push the changes to GitHub, then pull the branch in the other local repository? And risk everyone seeing my terrible Git commits? No~ooo.

The setup

What I do instead is connect the local repositories, so I can pull the changes from one local repository to another.

To set this up, I first find the path of the local clone of the repository I want to pull from, e.g. /home/tomdebruijn/work/main-repo. Then, in the repository I want to pull the changes into, set up a remote to that repository:

# Add a new remote with the name 'local' that points to the other local clone
git remote add local /home/tomdebruijn/work/main-repo

Then pull fetch changes from that repository and check out the branch I need.

# Fetch the contents of the other local clone
git fetch local
# Check out the other local clone's branch
git checkout <branch name>

Now I have the changes I committed in one local clone, available to me in another local clone as well, without having to sync it via an external SCM hosting provider.

Pull instead of push

Knowing this, we can also use this for other Git commands.

For example, you can push changes to another local repository clone, instead of pulling changes:

# Create a branch and add some changes to it
git checkout -b test-branch
echo "Test" > test.txt
git add .
git commit -m "Test commit"

# Push the branch to the other local clone of the repository
git push local test-branch

No need to fetch the changes in the other clone. It works like any remote repository.

Extra: Clone a local repository

You can also clone a local repository by pointing to its path.

# Go to another directory
cd /home/tomdebruijn/experiments
# Clone the local repository into this directory
git clone /home/tomdebruijn/work/main-repo 
# Open the newly cloned repository
cd main-repo
# List the repository contents
ls