Skip to content

Git · Technical

Git Tutorial

Learn to use Git like a professional and never let a single comma slip past you while programming your software applications

These are the most useful commands you will use day to day on software development projects under Git, the open-source distributed version control system. Sync, compare, merge and share the source code of your projects.

In this tutorial you will learn: git init, clone, add, commit, push/pull, branch management and advanced commands (rebase, cherry-pick, bisect). Estimated time: 15–20 min.

Quick reference table

Situation Command
Check the project status git status
Stage all changes git add .
Commit with a message git commit -m "message"
Push to the remote git push
Pull changes from the remote git pull
Create a branch and switch to it git switch -c new-branch
Merge a branch git merge branch-name
Set changes aside temporarily git stash
Bring set-aside changes back git stash pop
View the history as a graph git log --oneline --graph

Does your team use Git on Java or Spring Boot projects? At Arteco Consulting we integrate Git with CI/CD pipelines and sound development practices. Book a free consultation →

What is Git

Git is a version control system for file-based projects. It is distributed, so every copy of the project holds the entire history of changes. With it you can add, delete or modify the files of a software project and compare or recover the state of those files at any given moment. Each set of changes is committed to the Git repository, where it is recorded as a commit.

Optionally, a remote copy of the project under Git is kept somewhere on the Internet, so that one or more developers can exchange updates to the source files without losing track of the edits each of them has made separately. There are many platforms for this, and one of the best known is GitHub.

How to install Git

Git is a command-line tool that integrates well with the main code editors. Below we explain how to install it on each operating system.

Installing Git on Ubuntu

Installing Git on Ubuntu couldn't be easier. Just open a terminal and run apt, which downloads the package from the official repositories and sets the system up so it is ready to use.

We will install git and check that it runs without problems:

sudo apt install git

# check the installation
git --version

Installing Git on Windows

Git, created by Linus Torvalds, the father of Linux, ships ready-made packages for all the main platforms. Just go to the official Git project page and download the installer for your operating system, bearing in mind your system's architecture: 32 or 64 bits.

The Windows installer opens a wizard that shows a series of options along the way. There is no need to worry: the defaults are enough in most situations.

Once the process has finished successfully, check the installation by running Git with:

git --version

Installing Git on macOS

There are two ways to install Git on a Mac. The first is the installer (.dmg file) published on the official Git page for Mac. It is not the recommended route, however, because every update to the tool means installing it manually again, downloading and running the new installer.

On a Mac, the Homebrew package manager is recommended: it simplifies installation and keeps every application it manages up to date. What is more, most installations with brew happen in user space, without needing superuser access to the computer.

To install Homebrew on a Mac, run the following command in the terminal, taken from the project's official page:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Once it is installed, brew works much like Ubuntu's package manager, apt:

brew install git

After a few seconds the version control tool will be available globally in your terminal sessions. You can try it with:

git --version

Git terminology

Git uses a set of specific terms for everything it does, so if you are going to work with Git it is worth learning them all:

Term Meaning
repository Any copy of the project under Git's control and tracking. Git keeps all its information in a hidden directory inside the project itself, called .git.
remote repository A remote repository used as the synchronisation point for one or more developers. They all "push" their changes to the remote so that the rest of the team can get them.
commit A set of changes recorded in the repository, locally. It typically contains one or more changes to one or more files of the project, and therefore to the source code of the program being developed. It is the basic unit of the project's timeline as far as changes are concerned.
staging A preliminary phase in which the project's modifications are added to a temporary list that will end up as a commit. The staged changes can be discarded or turned into a commit in the repository. Changes means modifications, new files and also deleted lines, words or files.
branch Git lets a project evolve along several timelines. Branches represent potentially different evolutions of the files, which can be merged at a given point. For example, to keep versions 1.x and 2.x of the project in the same repository.
merge Used when you want to join two branches, carrying the commits of one over to the other. Very useful for bringing "experimental" changes — new features or bug fixes — into the "official" branch.
conflict Merging is not always automatic. If Git finds that the same file has been edited in different commits, it may not know which of those changes to keep when merging them. That is a conflict, and it has to be resolved by hand.

There are obviously many more technical concepts, but these are the basics you need to work with Git day to day. Let's see how they are applied.

Create an empty repository

To create a Git repository, from the root directory of the project we type:

git init

This command initialises the repository's internal indexes and references inside the .git directory. From then on we can add files, synchronise with other repositories and so on.

Create a copy of an existing repository

Creating an empty repository is sometimes useful, but normally we carry on with the work of an existing one. For that we need a remote repository that is reachable and from which we can download a complete copy. For example, if we are given a remote at https://github.com/user/project.git, we use that URL to make the copy:

git clone https://github.com/user/project.git

Git keeps a reference to the remote the copy came from, so that we can "push" the changes we make locally or download the changes other developers on the team make. It names that remote repository origin. You can add as many remotes as you like and push to or pull from any of them by name. If no name is given, origin is used by default.

Synchronise with a remote repository

We will see how to make a commit in a moment. For now, imagine we have already made one locally and, meanwhile, a colleague has pushed other changes to the remote. In that case, if we want to push our changes, Git makes us pull the remote's changes before pushing our own. So when we synchronise with a remote, we first run:

git fetch

This downloads a snapshot of the server's state; at this point our local repository realises it is one change behind the remote. The next step is to bring those changes into the working directory where our local copy of the project lives:

git pull

This command takes the remote changes we do not have locally yet and applies them to our files. If there is no conflict, the transfer is transparent and we will simply see that the files have changed. If there is a conflict, the file is left modified locally, waiting for us to review it by hand and finish with a commit that confirms the merge.

Following the case in which we had already made a commit, if there was a conflict we will push two commits to the remote: one with our change and another resolving the conflict. With no clash, we would only push the commit made locally.

Once any conflicts are resolved, we push all pending commits to the remote with the push operation:

git push

This uploads all the commits to the server, making them available to the rest of the team.

How to add remotes to Git

If we started from an empty repository created with git init, there is no remote configured to push changes to. One can be added easily with the following command:

git remote add origin https://github.com/user/project.git

Note that the remote has been named origin because it is the first and only remote assigned to the repository. The fetch and push commands let you say which remote to work with.

How to add files to Git

So we have a local repository and know how to synchronise it, but how do we record changes in Git? We simply need to know whether the change we made is to a file already under Git's control or to a new file Git knows nothing about yet. In an empty repository no file is under Git's control, so the first step is to add the file or files to Git.

Imagine we create a file called index.js in the empty repository. To add it to Git we run:

git add index.js

git add accepts wildcards, so there is no need to add files one by one. Advanced code editors even do this step for us.

When we run add, index.js becomes staged, ready to travel in a commit into the history of changes. If the file was already under Git's control, there is no need to add it.

How to make a commit in Git

Once one or more files are staged, the changes can be recorded in the local repository with a commit. Every commit in Git must come with a message:

git commit -m "add the index.js file"

This records the project's evolution and, if you work with a remote, you could then push. The push may fail if someone has pushed changes in the meantime, in which case you will have to fetch and pull first.

How to discard changes in Git

If we have local changes that have not been committed yet and we want to discard them, we can restore the project to the state of the last commit with:

git restore .

This discards all uncommitted local changes permanently. If instead we want to set them aside temporarily and pick the work up later, we use git stash:

git stash

The changes are kept on a stack. To bring them back at any time:

git stash pop

How to check the repository status

After several changes across the project's source files, it is easy to lose track of which lines have been edited. To see every modified file in the project we type:

git status

This gives an overview of the changed resources, but to see the detail of one in particular we ask Git to show us the differences:

git diff index.js

Git shows a rather plain text-based comparison. Fortunately, integrated development environments offer a far more attractive visual interface.

How to view the change history in Git

To show the change history for the whole project we use the log option:

git log

Each commit is identified by a hash such as c561ae54d2ccb9de92d1512a74ce2ea5b91acf88, and with that identifier we can see which changes were applied in that commit:

git show c561ae54d2ccb9de92d1512a74ce2ea5b91acf88

That way not a single comma that could stop your project from running properly will slip past you.

How to restore the project to a commit in Git

If we want to get the project back exactly as it was after a given commit, we can run the checkout operation:

git checkout c561ae54d2ccb9de92d1512a74ce2ea5b91acf88

To come back to the present, the following operation jumps forward in time to the latest commit:

git switch -

How to ignore files in Git

Some files should not be in the source control repository, for example build artefacts or files generated during compilation, such as .class, .exe, .dll and so on. They can be rebuilt whenever needed, so there is no point keeping them in the repository unless there is a compelling reason.

To tell Git to ignore certain files, you add a file (which is itself under Git's control) called .gitignore. It is a plain-text file at the root of the project listing specific files, patterns or directories that Git must ignore. For example:

*.log
target/
hs_error.log

As mentioned, this file should be under Git's control so that every developer on the team ignores the same files, so do not forget to add it to the next commit with:

git add .gitignore

How to create a branch in Git

As we have said, branches are different snapshots of the project that can evolve independently, although in most cases commits end up being carried from one branch to another. The most common use of branches is applying gitflow.

Gitflow is a way of organising branches to keep the project under control in all its phases. Put very briefly, gitflow says there must be a branch called main representing the version of the application in production, and a develop branch with additional commits on top of main, holding the work for the next release. Once develop is considered stable, its commits are carried over to main at the moment the new version is published and distributed. Gitflow recommends more branches, but these two are enough to illustrate how Git is used.

Note: in repositories created before 2021 the main branch may be called master.

By default, main is the initial branch and the one commits go to if no other branch is specified. But we can create a new branch from a commit to develop the project with experimental changes that may be discarded or end up in the final version of the software. Either way, we create a branch with:

git switch -c develop

The -c argument tells Git to create the branch if it does not exist. We can now make whatever commits we need. If you work with a remote, pushing this branch automatically creates one with the same name on the remote. To go back to the original branch we type:

git switch main

The new branch keeps the same history as the branch it came from, but changes made on it will not be in its predecessor, at least not until we merge the branches.

How to merge branches in Git

To merge two branches we must be on the target branch, using switch. The operation brings the commits of the named branch into the current one. So to bring the changes from develop into main, we first switch to main and then merge with merge:

git switch main
git merge develop

This can lead to conflicts if main has changes that were not made on develop. If so, we will have to make a manual commit resolving the conflict or conflicts. Remember that if you work in a team with a remote, you must push to share the changes with everyone else.

How to delete branches in Git

If you have finished with a local branch and want to delete it, just tell Git so:

git branch -d develop

You may want to delete the branch on the remote repository rather than locally; in that case the command changes slightly:

git push origin --delete develop

Bear in mind that if the rest of the team pulled the deleted branch, it will still exist in their copies even though you have deleted it on the reference remote.

Advanced Git commands

Once you have the fundamentals, these commands make the difference between basic and professional use:

git rebase — rewriting history cleanly

Rebase moves a set of commits from one branch to another point. Unlike merge, it does not create an extra merge commit, so the history stays more linear and easier to read:

git rebase main

Useful for bringing main's changes into your feature branch before opening a pull request, avoiding unnecessary merge commits.

git cherry-pick — bringing over specific commits

Applies one specific commit from another branch to the current branch, without merging the whole branch:

git cherry-pick a1b2c3d4

Very handy for applying a production hotfix to develop without pulling in other changes.

git bisect — finding the commit that introduced a bug

Runs a binary search through the history to find the exact commit that introduced an error:

git bisect start
git bisect bad                    # the current state is broken
git bisect good v1.2.0            # this version worked

Git keeps checking out intermediate commits; you mark each one as good or bad until the culprit is isolated.

git stash — keeping unfinished work

We saw it earlier, but it has options that are useful day to day:

git stash push -m "wip: new user endpoint"     # named stash
git stash list                                  # list all stashes
git stash apply stash@{2}                       # apply a specific stash
git stash drop stash@{0}                        # delete a stash

git log — exploring history with filters

git log --oneline --graph --all        # visual tree of all branches
git log --author="Name"               # commits by one author
git log --since="2 weeks ago"         # recent commits
git log -- path/to/File.java          # history of a single file

Conclusion

Git is the most widely used version control tool in professional software development. Mastering everything from the basic commands (init, add, commit, push) to the advanced ones (rebase, bisect, cherry-pick) is what separates a developer who simply "saves code" from one who manages the project's evolution deliberately.

Integrated development environments (IntelliJ IDEA, VS Code) offer all these operations through a visual interface, but knowing the commands lets you act precisely when the interface falls short.

Does your team work with Java and need to modernise its development practices? At Arteco Consulting we combine Git with CI/CD pipelines, TDD and clean architectures so that projects reach production with quality and speed. Get in touch — the first consultation is free.

Ramón Arnau Gómez

Ramón Arnau Gómez

Director de Arteco

Programador Java desde 2003. Ingeniero Informático (UIB), Máster en Tecnologías de la Información (UIB), Máster en Administración y Dirección de Empresas (UAX). Arquitecto Java

More articles by Ramón