There are times you already started to write code on your local machine with local Git database. You created a repository on GitHub and you want to upload your local Git repository to it. Let’s see how we can do it.
Start Local Git Repository
I’m using a Linux Mint as my desktop right now but as long as you have Git installed on your machine, you should be able to do the same whether you are on Mac, Windows or Linux.
Let’s create a local directory where you are planning to store your code. I’m going to create test-repo directory in my home directory.
$ mkdir test-repo $ cd test-repo
I’m now going to create a local Git repository (database) by running the following command.
$ git init
I’m creating a test.java file within the directory. It doesn’t really matter what you have in the file at the moment. Now let’s check the status.
$ git status
You will see an output like the following.
$ git status On branch master No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) test.java nothing added to commit but untracked files present (use "git add" to track)
We will now stage the untracked file.
$ git add --all
Now the untracked file has been staged to be ready to be committed to the local Git database. Let’s commit it now.
$ git commit -m 'first commit'
The command above commits the change to the local Git database. Now we want to upload the commit to GitHub but we don’t have GitHub repo. Let’s create one now.
Create a Repository on GitHub
- Login to GitHub. (Create an account if you haven’t)
- Click New button to create a new repository.
- Enter repository name and click Create repository button.
Add the Remote Repository to Local Git
For the local Git repo to be able to talk to the GitHub remote repo, we need to add the URL to the local repo. I’m going to omit the process of generating SSH key and register it on GitHub. For details, please see this link.
Back to your terminal within the test-repo, run the following command to add the GitHub repo as its remote repo. Make sure to change the URL according to your own repo on GitHub.
$ git remote add origin email@example.com:hiriumi/test-repo.git
Now you are ready to push the local Git to the remote repo on GitHub. If you run the following command, you will be able to push the file to GitHub.
$ git push --set-upstream origin master
After it’s done, you don’t have to type the whole
git push --set-upstream origin master for your next push. After you commit, all you need to do is
I just wanted to summarize what I usually do when I start a new project. The same technique can be applied for GitLab and Bitbucket for sure.