This article demonstrates several scenarios when creating and working with a Git repository.
You are given a remote git repo
For example:
git@bitbucket.org:demo/git-demo.git
Scenario 1
- The remote repository is empty
- You have not created any files locally. (No local repo)
This scenario is straightforward. You can clone the remote repository and start working.
git clone git@bitbucket.org:demo/git-demo.git
Scenario 2
- The remote repository is empty
- You already creates some files locally
Assuming you have already started some development before receiving a remote repo.
mkdir git-demo && cd git-demo
git init
pico test.txt
git add test.txt
git commit -m "my first file"
In this scenario, you must add the remote repo using the git remote command.
git remote add origin git@bitbucket.org:demo/git-demo.git
Then you can continue with your work or push your local commits to the remote repo.
git push origin main
Scenario 3
- The remote repository already has some files (For example, README.md or .gitignore)
- You have not created any files locally (No local repo)
We can follow the same as scenario 1.
git clone git@bitbucket.org:demo/git-demo.git
Scenario 4
- The remote repository already has some files (For example, README.md or .gitignore)
- You already creates some files locally
Assuming you have already started some development before receiving a remote repo. At the same time, the remote repo contains some other files.
First, you need to add the remote repository.
git remote add origin git@bitbucket.org:demo/git-demo.git
Since we will encounter a situation where the reconciliation of branches is required, we need to specify the strategy.
# Run one of the following commands, I usually select merge.
# For more reading - https://www.atlassian.com/git/tutorials/merging-vs-rebasing
git config pull.rebase false # merge
git config pull.rebase true # rebase
Next, we want to sync the remote files. We use the git pull command and notice that an error occurs. This is because, by default, git does not allow the merging of 2 branches without a common base.
git pull origin main
From bitbucket.org:demo/git-demo
* branch main -> FETCH_HEAD
fatal: refusing to merge unrelated histories
We can tell git this is intended by:
git pull origin main --allow-unrelated-histories
After this command executes, git creates a new revision to track this merge. You can use the vi prompt to enter the commit message, or if you are not familiar with vi, you can use the git commit command.
git commit -m "Merge with remote"
Finally, you can push this commit to remote.
git push origin main