How to simulate a remote repo locally in order to practice git
It can be troublesome to practice git using a remote repository. Fortunately, there is a simple way to set up a git environment locally so as to play with git push, pull & fetch
without requiring a “real” remote repository.
In order to simulate interactions between two developers, say John & Mary, simply create two directories on your machine like so:
mkdir john mary
Then create another directory locally that is going to act as a remote:
mkdir local
Then within the local directory, we are going to initialize a bare git repository: that means a repo without any “working tree” i.e. there won’t be any checked out files in this repository.
git init --bare
Then, let’s move on to John’s setup by connecting him to the local repo. From John’s directory, let’s init a git repo & connect it to the local repository:
git init
git remote add local ../local # Assuming "john", "mary" and "local" directories are at the same level
Optional: you can also set the local user.name
to John like so:
git config user.name John
This will change the name of the git user locally only so that commits from John and Mary have different user names.
Then, repeat the same process for Mary:
cd mary
git init
git remote add local ../local
git config user.name Mary
Congratulations: you are all set in order to practice git push, fetch & pull
without hitting the network:
From Mary’s directory, run the following commands:
touch foo.txt
echo "Hello world" > foo.txt
git add foo.txt
git commit -m"Introduce greetings in English"
git push local master # Assuming "master" is the name of the default branch (it can be "main" also)
From John’s directory, just run:
git pull local master
Now you should see Mary’s commit in John’s repo!!
Conclusion: this technique allows you to practice all git commands locally without requiring you to use the network.