Git tutorial
in Tutorial with 7 comments
Git tutorial
in Tutorial with 7 comments

Yes, this is a novice tutorial just like the last article. It mainly records my common Git operations and some tips and precautions. I hope it can help you.

This tutorial requires readers to understand Command Line. If you don't understand it, please take a look at my other article: here

Basic knowledge

What is Git?
Git is a collection of command line tools that can help you track and record changes to files (source code, images, etc.). With it, you can restore old versions of projects, and even compare, analyze, merge and modify them. This process is called version control. In addition to Git, we also have SVN, Mercurial, Perforce, CVS, Bitkeeper, etc. to help us achieve version control

Git's characteristics?
Git is distributed. We don't need a master server to host various versions of our projects. Instead, it is a folder working on your local disk. This folder stores Git managed projects, which we call repository. At the same time, you can also put a copy of your project online, such as Github or Gitlab, to meet the needs of multi person collaboration and project code sharing

Install Git

Only the installation of macOS is listed here, mainly through homebrew To install

 brew install git

If you are too new, here are two more client software, GitHub Desktop and Sourcetree

Configure Git

After installation, we need to add some configuration information. There are many configuration items to be filled in for other Gits. Here we will fill in the most important two items first, user.name and user.email

Open the terminal and enter the following

 git config --global user.name "Chakhsu Lau" git config --global user.email  chakhsu@email.com

there "Chakhsu Lau" and chakhsu@email.com It needs to be replaced by yours

Configure these two items so that each Git operation will bring the information you entered above, so that you can track who is doing each operation

For more information, see: here

Create Repository

As we mentioned above, Git manages and stores files in folders on your disk. Enter the following at the terminal

 cd ~/node mkdir git-demo cd git-demo git init

git init This command will tell Git that this folder is special, and it will also create another .git Folders are used to store historical and configuration information

The following information will be displayed after initialization

 Initialized empty Git repository in /Users/chakhsu/node/git-demo/.git/

It indicates that our Git Repository has been created, but it is empty. We need to create a file hello.txt

 touch hello.txt

View Repo Status

git status It can help us view the status of the current repository, including which files have been updated, which are new, and which have been deleted

 git status On branch master Initial commit Untracked files: (use "git add <file>..." to include in what will be committed) hello.txt nothing added to commit but untracked files present (use "git add" to track)

The information returned here is the file we added above. This information tells us that the file is new, but git does not know whether to track it or choose to ignore it, so we enter into the study of Git Staging

Operation Stage Status

Git has a concept of "staging area". You can think of it as your schoolbag in your student days. There are all kinds of homework books and books (your files) in it. Some of these homework books have completed their homework, some have completed part of it, some have not done it yet, and some are even new. You can git add Select which workbooks need to be submitted, and these selected workbooks will enter the stage state, waiting for the final git commit

If one of the files is selected, it is as follows

 git add hello.txt

If you select All, then

 git add -A

If only modified files are selected, excluding new files and uncommitted files, then

 git add .

Let's execute the first selection here and check the Git status, as shown below

 git status On branch master Initial commit Changes to be committed: (use "git rm --cached <file>..." to unstage) new file:   hello.txt

It turns out that Git already knows our hello.txt Ready to be submitted

If we want to cancel hello.txt The stage status of this file (cancel add) is as follows

 git reset hello.txt

Operation Commit Status

Commit the Staging project, that is, give the repository where the current project is located a time point status, and add a description to briefly describe the content of this commitment, just like the usual snapshot, we can go back to see how it works at any time

 git commit -m "Initial commit. " [master (root-commit) b1adc8d] Initial commit. 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 hello.txt

In this sentence, skip the editor and directly enter the commit brief, complete the submission, and display some information

We can also do this, as follows

 git commit -am "Initial commit. "

This sentence means, execute first git add . Skip the editor and enter the commit brief to complete the submission

If we want to modify the brief description of the last commit, as follows

 git commit --amend

Then jump out of the editor and let you modify the current brief

If we want to cancel the just commit but keep the modified file or project, as follows

 git reset HEAD^ --soft

If we want to return to the clean state of the last commit, as follows

 git reset HEAD^ --hard

Remote Repo

The above basic knowledge is operated locally, and all the commits only exist in the project .git Folder. Although the local repository is sufficient, in most cases, we need to share or deploy our projects online, or host them to remote repositories

Connect Remote Repo

At this time, we need to register an account on Github, and then create an empty Repository on it. Suppose we have already registered and created a Repository

The address of this repository is https://github.com/chakhsu/lilicia.git , the address here needs to be changed to your own, which is only used as a tutorial

Then, open the terminal and input the following

 git remote add origin  https://github.com/chakhsu/lilicia.git

A project may have multiple remote repositories. To distinguish different remote repositories, we need to give them different names origin Is the name of this repository

Upload to server

Just now we have connected to remote repositories, but there is nothing on it. We need to upload committed files to remote repositories

 git push origin master Counting objects: 3, done. Writing objects: 100% (3/3), 211 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To  https://github.com/chakhsu/lilicia.git * [new branch]      master -> master

there git push You are also required to enter your github user name and password to run push

also git push It has two parameters. One is the name of the remote Repo (we call it origin here) and the other is the branch push (master is the default branch of each Repo)

Clone Repo

Above, I have uploaded the local Repo to Github, so that others can view and browse the things on the Repo on Github, and even clone them to their own local, as follows

 git clone  https://github.com/chakhsu/lilicia.git

Repo will be automatically created locally, and the local Repo version is Github version

Get Updates

You have updated Repo, and others can go through git pull Update online Repo to your local Repo

 git pull origin master From  https://github.com/chakhsu/lilicia * branch             master     -> FETCH_HEAD Already up-to-date.

Pull here refers to downloading remote Repo and merging local Repo

Similarly, you can obtain others' Repo in this way

Branches Management

When we need to develop a new function, the best practice is to copy the original project and complete the development on its copy, which we call Branches. This branch has its own version control. Each modification will be different from other projects until you decide to merge them.

Benefits of branch management:

Create Branch

The default branch of each Repo is called master , create additional branches, use git branch <name> , as follows

 git branch baranch-one

perhaps git checkout -b <name>

 git checkout -b  baranch-one

It means to create the branch and switch to the branch

So far, our baranch-one After the creation, follow the master The version on the branch is consistent

View Branch

List all local branches

 git branch

List all remote branches

 git branch -r

List all local and remote branches

 git branch -a

Switch branch to baranch-one

 git checkout baranch-one

Merge Branch

Above, we have created branches baranch-one , we need to select the branch and enter, as shown below

 git branch baranch-one * master
 git checkout baranch-one

Then we create feature.txt , and add and commit it

 touch feature.txt git add feature.txt git commit -m "New feature complete. "

Next, we need to switch the master branch

 git checkout master

The next step is to merge branches

 git merge baranch-one

After merging, the original baranch-one It is unnecessary and can be deleted as follows

 git branch -d baranch-one

Advanced Tutorial

This part may be used in our daily development process. It is OK to know and use it

Check commits

Each time we commit, we randomly generate a unique ID, which is composed of a string of numbers and letters. If we want to view all commits and their IDs, we can use git log , as follows

 git log commit 108e80c5d06dc802c2000d7085dcd2bd4162e666 Author: Your Name < youname@mail.com > Date:   Sun Feb 26 00:56:14 2017 +0800 Initial commit.

To view a specific commit, we can use git show [commit] , as follows

 git show 108e80c5 commit 108e80c5d06dc802c2000d7085dcd2bd4162e666 Author: Your Name < youname@mail.com > Date:   Sun Feb 26 00:56:14 2017 +0800 Initial commit. diff --git a/hello.txt b/hello.txt new file mode 100644 index 0000000..e69de29

If you want to check the difference between two commits, we can use git diff [commit-from].. [commit-to] , we won't show it here

Restore files

In fact, it has already been mentioned above. Here's another explanation

 git checkout hello.txt
 git checkout 108e80c5 hello.txt

For these two commands, the former is to hello.txt Restore to the most recent commit state, and the latter specifies to restore to a commit state

Handling merge conflicts

Most of the time, we often need to work with multiple people to develop together. We constantly create branches and merge branches. In this process, there may be merge conflicts.

Let's look at an example. First, we created two branches, called branch-chakhsu and branch-ping , you should write a function in the same file to display all elements of the array

Assume that the same file is showarray.js

branch-chakhsu The branch is written as follows

 // Use a for loop to console.log contents. for(var i=0;  i<arr.length; i++) { console.log(arr[i]); }

branch-ping The branch is written as follows

 // Use forEach to console.log contents. arr.forEach(function(item) { console.log(item); });

Then we merge the above two branches, and an error will be reported

 git checkout master git merge branch-chakhsu git merge branch-ping Auto-merging showarray.js CONFLICT (content): Merge conflict in showarray.js Automatic merge failed; fix conflicts and then commit the result.

Then we open showarray.js , found

 <<<<<<< HEAD // Use a for loop to console.log contents. for(var i=0;  i<arr.length; i++) { console.log(arr[i]); } ======= // Use forEach to console.log contents. arr.forEach(function(item) { console.log(item); }); >>>>>>> Ping's commit.

<<<<<<< HEAD and ======= Between are the commit contents of the branch where we are currently located

======= and >>>>>>> Ping's commit. Is what we want to merge branch-ping Branched content

At this time, we have to decide whether to keep both, or choose one of them or change it to the content we want. Here, change it to the content we want

delete <<<<<<< HEAD and >>>>>>> Ping's commit. The content between is modified as

 // Not using for loop or forEach. // Use Array.toString() to console.log contents. console.log(arr.toString());

Add the modified file to the stage status, and then commit again, as shown below

 git add showarray.js git commit -m "Array printing conflict resolved. "

The merge conflict is resolved. When we have conflicts, the processing steps are as follows

Configure. gitignore

Many times, we don't need all the files git add , especially when we use git add -A This command selects all files to enter the stage state. What can be avoided? That's configuration .gitignore file

The following files or folders can be ignored

According to the above list, we can modify .gitignore The contents of the file are

 *.log build/ node_modules/ .idea/ my_notes.txt

summary

After writing for a long time, I also read a lot of materials, which is also a big review. In addition, the article may have errors, please correct

Here is a list of materials found in writing this tutorial, hoping to help you

The tutorial is compiled with practice and reference to the following articles

tutorialzine.com/2016/06/learn-git-in-30-minutes/
blog.gogojimmy.net/2012/01/21/how-to-use-git-2-basic-usage-and-worflow/

Responses
  1. The theme is beautiful and simple.

    Reply
    1. @Collected Works of Wang Yikai

      Thank you~ 😙😙

      Reply
  2. Thank you, the blogger. I want to reprint it and record it. I forgot the agreement of the blogger (I will write the source of the reprint and respect the original)

    Reply
    1. @Note Yi

      Well, turn around~

      Reply
      1. @Chakhsu

        Transferred, this blog link https://biji.eu/2017/55.html Thanks again.
        When I come back from learning something, I want to link with my blogger friends

        Reply
  3. Marked. Quite helpful~

    Reply
    1. @Wayne

      Thank you~~ 😝

      Reply