Git has gained popularity in recent years. Version code control systems are used by huge open source projects like Linux, thousands of contributors, teams of all sizes, independent developers, and even students.
Beginners are often daunted by all the arcane commands and arguments git requires. Git commands are also frequently asked in interviews. You can start with some of the most common ones and work your way up from there.
basis
Git is a collection of command-line utilities that track and log changes in files (usually source code, but can track any file you want). With it, you can restore old versions of projects, compare, analyze, merge changes, and more. This process is called version control. There are many version control systems that can do this. You’ve probably heard of some of them –SVN, Mercurial, Perforce, CVS, Bitkeeper, and more. Git is decentralized, which means it doesn’t rely on a central server to keep older versions of files. Instead, it runs entirely locally, storing this data as a folder on a hard disk, which we call a repository. However, you can also store copies of your repository online, making it easy for multiple people to collaborate and use the same code. This is what sites like GitHub and BitBucket use.
1. Install Git
Installing Git on your device is simple: Linux – just open a new terminal and install Git through your distribution’s package manager. For Ubuntu the command is: sudo apt-get install git Windows – we recommend git for Windows because it provides a GUI visual client and a BASH command-line emulator. OS X – The easiest way is to install the self-service software and brew Install Git to run from a terminal. If you are an absolute beginner, a graphical Git client is a must. I highly recommend using GitHub Desktop and Sourcetree, but there are many other good and free ones online. Even with GUI applications, it’s still important to know basic Git commands, so this will be the only focus for the rest of this article.
2. Configure Git
Now that we have Git installed on our computer, we’ll need to add some quick configuration. There are plenty of options to fiddle with, but let’s set the most important ones: our username and email. Open a terminal and run these commands:
$ git config --global user.name "My Name"
$ git config --global user.email [email protected]
Copy the code
Every action we make in Git is now tagged with our name and address. That way the user always knows who did what and everything is more organized.
3. Create a new repository – git init
As we mentioned earlier, Git stores its files and history directly in the project folder. To create a new repository, we need to open a terminal, navigate to our project directory, and run Git init. This will open the Git specific folder and create a hidden.git directory with the repository’s history and configuration.
Create a folder called git_exercise on your desktop, open a new terminal and enter the following:
$ cdThe Desktop/git_exercise/ $git init command line should output: Initialized empty Git repositoryin /home/user/Desktop/git_exercise/.git/
Copy the code
This means that ours has been successfully created, but the content is still empty. Now create a simple text file called hello.txt and save it in the git_exercise folder.
4. Check the git status
Git status is another must-know command that returns information about the current state of the repository: confidence that everything is up to date, what is up to date, what has changed, and so on. Running git status in our newly created Log should return the following:
$ git status
On branch master
Initial commit
Untracked files: (use “git add …” to include in what will be committed)
hello.tx
Copy the code
The returned message indicates that hello.txt was not traced. This means that the file is new, and Git doesn’t know whether it should keep track of changes made to the file, or ignore it. To identify the new file, we need to classify it.
Git add has a concept of “staging area”. Think of it as a blank canvas that holds the changes you want to commit. It starts out empty, but you can add files (even single lines and parts of files) git add with commands, and finally commit all files (creating a snapshot) git commit. File:
$ git add hello
.
txt
Copy the code
If we want to add everything to the directory, we can use:
$ git add
-
A
Copy the code
Again checking the status input git status should return a different output from the previous one.
$ git status
On branch master
Initial commit Changes to be committed:
(use "git rm --cached ..."to unstage)
new file: hello.txt
Copy the code
Our papers are ready for submission. The status message also tells us what has changed to the file in the staging area – in this case a new file, but it can be modified or deleted, depending on what git add has happened to the file since the last time.
6. Commit – git commit
A commit represents the state of our warehouse at a given point in time. It’s like a log that we can go back and see what we took.
To create a new commit, we need to have at least one change added to the staging area (let’s do git add), then run the following command:
$ git commit
-
m
"Initial commit."
Copy the code
This creates a new commit that contains all the changes from the staging area (add hello.txt). The -M “Initial Commmit “section is a user-defined description that summarizes the changes made in this commit. Committing often and always writing meaningful commit messages is considered a good practice for developers.
Remote warehouse
Now our commit is local – it only exists in the.git folder. While the local repository itself is useful, in most cases we want to share our work and deploy it to a server or repository hosting service.
1. Connect to a remote repository with git remote add
In order to upload something to a remote response, we first have to establish a connection. In order to cooperate with in this paper, our store address will be https://github.com/Tamic/novate. We recommend creating your own empty repository on GitHub, BitBucket, or any other service. Registering and setting up may take a while, but all services provide good step-by-step guidance documentation to help you.
To connect our local repository to the repository on GitHub, we execute the following line in the terminal: file:
Connect to the remote server
$ git remote add origin https
:
//github.com/Tamic/novate.git
Copy the code
A project may have multiple remote repositories at the same time. In order to distinguish them, we give them different names. Traditionally the primary remote repository in Git has been called Origin.
2. Upload to server – git push
Now it’s time to move our local submissions to the server. This process is called push and is done whenever we want to update the remote repository. The Git command does this, Git push, and takes two parameters – the name of the remote repo (which we call our origin) and the branch to push to (master is the default branch for each feedback).
$ git push origin master
Counting
objects
:
3
,
done
.
Writing
objects
:
100
%
(
3
/
3
),
212
bytes
|
0
bytes
/
s
,
done
.
Total
3
(
delta
0
),
reused
0
(
delta
0
)
To https://github.com/Tamic/novate.git *
[new branch ] | master -> master
Copy the code
Depending on the remote service you use, you will need to verify your password and account number. If all goes well, when you enter the remote repository you created earlier in your web browser, hello.txt should be there and ready to read.
Git clone
At this point, you can view and browse the remote repository on Github. They can download it locally and get a full working copy of the project using the following git clone command:
$ git push origin master
$ git clone https
:
//github.com/Tamic/novate.git
Copy the code
Automatically create a new local repository and configure the Github version to be remote.
4. Get changes from the server – git pull
If your repository is updated, you can download the changes using a single command — git pull:
$ git pull origin master
From
https
:
//github.com/Tamic/novate.git
*
branch master
->
FETCH_HEAD
Already
up
-
to
-
date
.
Copy the code
Since no one else has submitted a new file or modified it since we cloned it, there are no changes when downloading it.
branch
When developing a new feature, it is also considered a good practice for developers to consider a copy of the original project, called branching. Branches have their own history and isolate changes between them until you decide to merge them together. This is due to the following reasons:
A working, stable version of the code will not be broken. Many features can be developed immediately and safely by different people themselves. Developers can work on their own branch without the risk of changing the code base because of someone else’s work. When in doubt, you can develop multiple versions of the same feature on different branches and compare them.
1. Create a new branch – Git Branch
The default branch of each repository is called the Master branch. To create more branches, use the following git branch command:
$ git branch amazing_new_feature
Copy the code
This just creates the new branch, which at this point is exactly the same as our trunk.
2. Branch — Git Checkout
Now, when we run Git Branch, we see two options available:
$ git branch
amazing_new_feature
*
master
Copy the code
Master is the current branch and is marked with an asterisk. However, we want to use our new feature, so we need to switch to another branch. This is done using the Git checkout command, which takes one parameter – the name of the branch to switch to.
$ git checkout amazing_new_feature
Copy the code
Git merge
Git’s “amazing new feature” will become yet another text file called feature.txt. We’ll create it, add it, and commit it.
$git add feature. TXT $git commitCopy the code
Once the new functionality is complete, we can cut back to the main branch.
$ git checkout master
Copy the code
Now, if we open our project in the file browser, we will notice that feature.txt has disappeared. That’s because we went back to the master branch where feature.txt was never created. To achieve this goal, we need to merge the two branches of Git Merge and apply the changes made in the amazing_new_feature to the main version of the project.
Git merge amazing_new_featureCopy the code
The main branch is now up to date. The awesome_new_feature branch is no longer needed and can be removed.
git branch -d amazing_new_feature
Copy the code
Advanced operation
In the final section of this article, I’ll introduce some of the more advanced techniques that are likely to come in handy at work. 1. Check for differences between commits Each commit has a unique ID as a string of numbers and symbols. To see a list of all commits and their ids, we can use git log:
$ git log
commit ba25c0ff30e1b2f0259157b42b9f8f5d174d80d7
Author
:
Tutorialzine
Date
:
Mon
May
30
17
:
15
:
28
2016
+
0300
New
feature complete
commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author
:
Tutorialzine
Date
:
Mon
May
30
16
:
30
:
04
2016
+
0300
Added
content to hello
.
txt
commit
09bd8cc171d7084e78e4d118a2346b7487dca059
Author
:
Tutorialzine
Date
:
Sat
May
28
17
:
52
:
14
2016
+
0300
Initial
commit
Copy the code
As you can see, ids are quite long, but when working with them, there’s no need to copy the whole thing – the first few symbols are usually enough.
To see what’s new in the commit, run git show [commit] :
$ git show b10cc123
commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author
:
Tutorialzine
Date
:
Mon
May
30
16
:
30
:
04
2016
+
0300
Added
content to hello
.
txt
diff
--
git a
/
hello
.
txt b
/
hello
.
txt
index e69de29
..
b546a21
100644
---
a
/
hello
.
txt
+++
b
/
hello
.
txt
@@
-
0
,
0
+
1
@@
+
Nice
weather today
,
isn
't it?
Copy the code
To see the difference between any two commits, use git diff[commit-from].. [commit – to] syntax:
$ git diff
09bd8cc
..
ba25c0ff
diff
--
git a
/
feature
.
txt b
/
feature
.
txt
new
file mode
100644
index
0000000.
.
e69de29
diff
--
git a
/
hello
.
txt b
/
hello
.
txt
index e69de29
..
b546a21
100644
---
a
/
hello
.
txt
+++
b
/
hello
.
txt
@@
-
0
,
0
+
1
@@
+
Nice
weather today
,
isn
't it?
Copy the code
We’ve compared the first commit to the last commit, so we see all the changes. This task is usually made easier by using the Git Difftool command, which allows a graphical client to display all the differences.
2. Restore the file to the previous version
Git allows us to return any selected file to a commit. This is done using git checkout, the familiar command we used to switch branches, but can also be used to switch between commits (it is common in Git to have one command for multiple seemingly unrelated tasks). In the following example, we’ll take hello.txt and undo everything we’ve done since the initial commit. To do this, we must provide the id of the commit we want to return, as well as the full path to our file.
$ git checkout 09bd8cc1 hello.txt
Copy the code
3. Fix the commit
If you notice that you typed a typo in your commit message, or that you forgot to add a file and you see it after committing, you can easily fix it. This will add everything from the last commit to the staging area and try a new commit. This gives you a chance to resolve your submission information or add more files to the temporary area.
For more complex fixes that weren’t in the last commit (or if you’ve already pushed changes), you must use Git Revert. This will take all the changes introduced by the commit, roll them back, and create a new commit that does the opposite.
The latest commit can be accessed by the HEAD alias.
$ git revert HEAD
For other commits, it is best to use an ID. $ git revert b10cc123
When restoring older commits, keep in mind that merge conflicts are likely to occur. This happens when a file is changed by another more recent commit, and now Git can’t find the right rows to recover because they’re not there anymore.
4. Resolve post-merger conflicts
In addition to the situations described above, conflicts often arise when merging branches or involving other people’s work. Sometimes conflicts are handled automatically by Git, but sometimes the person handling these conflicts must decide (usually culling) which code stays and which gets removed.
Let’s look at an example where I merge two branches called john_branch and tim_branch. Both Zhang and Li write a function in the same file that displays all the elements in the array.
Chang is using the for loop:
/ / useforLoop through the console.log content.forVar I = 0; i < arr . length ; I ++) {console.log(ARR [I]); Xiao Li likes itforEach: // useforEach to console.log. arr .forEach (function(item) {console.log(item); }); They all commit code on their branches. If they now try to merge two branches, they see the following error message: $git merge tim_branch auto-merging print_array.js CONFLICT (content): Merge CONFLICTin
print_array
.
js
Automatic
merge failed
;
fix conflicts
and
then
commit the result
.
Copy the code
Git cannot merge branches automatically, so it is now up to developers to resolve conflicts manually. If they open the file where the conflict occurred, they will see that Git inserted a tag on the line where the conflict occurred.
<<<<<<< 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
);
});
>
>>>>>> xiaozhang's commit.
Copy the code
On =====, we have the current HEAD submission, and under conflict. This way we can clearly see the differences and decide which version is better, or write a new version together. In this case, we go to the latter, rewrite the whole thing, and remove the tag to let Git know we’re done. // Do not use loops or forEach. // Use array.tostring () for the console.log content. Console.log (arr.tostring ());
When everything is set up, a merge commit must be completed to complete the process. $ git add
A $ git commit
M “Conflict resolution.” As you can see, this process is very annoying and can be very difficult in large projects. Most developers tend to GUI client download (https://git-scm.com/download/gui/linux) with the help of conflict resolution, this makes things easier. Run the graphics client using Git MergeTool.
5. Set. Gitignore
In most projects there are files or entire folders that we don’t want to commit. Git add-a ensures that they are not accidentally included in our content by creating.gitignore files: manually create A text file named.gitignore and save it to your project directory. Inside, list the names of files/directories to ignore, each on a new line. .gitignore itself must be added, committed, and pushed, just like any other file in the project. A good example of files being ignored are: log files. Task runners create node_modules folders in node.js projects. Personal developer notes are folders created by ides such as NetBeans and IntelliJ
Disallow all of the above. Gitignore will look like this: *.
log
build
/
node_modules
/
.
idea
/
my_notes
.
txt
Copy the code
Slashes at the end of some lines indicate that this is a folder, and we ignore everything in the recursion. Asterisks are usually used as wildcards.
Write in the last
Git is quite complex and offers many more features and tricks. If you want to learn more about recommended learning resources: the official Git documentation, including a full book and video lessons – here (git-scm.com/doc). Getting Git right – Atlassian’s collection of tutorials and articles – here (www.atlassian.com/git/). A list of GUI clients – here (www.git-scm.com/downloads/g… Git cheat sheet (PDF) – here. Services.github.com/on-demand/d…
Online tool for generating.gitignore files – here. www.gitignore.io/