Saturday, April 27, 2019

Git Basic usage – git init and git clone

This note will go through two ways to generate git repository:
  1. Push existing project to remote repository
  2. Clone remote repository and push the new changes back

Push exiting project to remote repository

First, let’s create a new folder in our local directory, and run the following instructions to generate a new file.

$ mkdir GitTest

$ cd GitTest

$ touch test.html

$ ls -al

Then you can inspect the following screen which indicates that we only have one file called “test.html” under GitTest directory.


Second, use “git init” to convert this “local directory” to “git repository”

$ git init

$ ls -al

After that, .git sub-directory was created after executing “git init”.



As being a git repository, you can start to use “git status” to check this git repository status.

$ git status



Third, using the following instructions to add and commit the changes

$ git add .

$ git commit -m “init”

$ git status

After that, the status will be shown as “working tree clean”.



In the end, we want to push our local commits to central repository. In order to do that, we need to add the remote connection to this local repository. Before starting, let’s use “git remote” command to check it first.

git remote -v

We can tell that there is no remote reference in this local repository.




Using the following instructions to add remote reference.

Before doing that, you need to go to your git provider to create an empty repository first.

In this example, my new repository of my git provider is called “GitTest”.

$ git remote add origin https://github.com/chengys1986/GitTest.git (your own url)

$ git remote -v

Then, you can see you added remote reference successfully.




Now, you are able to use the following instruction to push your local commits to remote repository.

$ git push origin master




Then checking your git provider page, and you will see a new commit!


Clone from remote repository and push new changes back

In order to demonstrate it, please delete the local git repository we created from previous experiment.

$ rm -r GitTest/

Getting URL of your previous remote git repository from your git provider, and using “git clone” to clone it!

$ git clone https://github.com/chengys1986/GitTest.git

After that, you can see the directory is copied from remote to local, and the .git sub-directory is created as well.



Once our local repository is created by cloning command, the remote will be setup automatically.

(For git init section, we need to use “git remote add” command to add the remote reference)



Then use “git status” to check whether the code is clean or not.



Using the following instructions to commit a new change.

$ touch index.html

$ git status

$ git add .

$ git commit -m ‘second commit’
 

Using the following command to push to remote repository.

$ git push origin master


Then checking your git provider page, and you will see a new commit!