Git Tutorial: A Complete Beginner’s Guide

Collaborative software development has never been easier. Thanks to Git, you can easily monitor the modifications and contributions made to your projects. Stick with this Git tutorial and learn the software’s workflow, common commands, and other basic concepts.

What is Git?

git

Git is a Version Control System (VCS), developed by Linus Torvalds (creator of Linux) back in 2005. It can be used to track changes in any files, but it is commonly used to develop software.

So, what are the advantages of Git? Let’s take a look:

  • Track all files — developers can easily view the files in development, restore the previous version of a file, and understand what’s changed when you release a new version of your software.
  • Collaborate better — modifications made by several developers can be easily merged.
  • Work efficiently — you can work on multiple features at once by utilizing branches, which we’ll cover later in this article.
  • Cross-platform — it can be installed on WindowsmacOS, and Linux

If you work alone, you can save the whole database in your local repository. However, when you work with other developers, the project should be stored and shared in a remote repository (or master repository), which is hosted on a platform like Github.

Since Git is a distributed VCS, users don’t have to access the master repository to create modifications. They can clone (copy) the master repository to their local machine, then modify the files without connecting to the network.

On the flip side, users of centralized VCS like SVN or CVS have to connect to the master repository to create changes. That’s why Git is the better choice if you want to work flexibly.

To understand the concept better, we will show you how to use Git in the next section of the tutorial!

Git Workflow

Every local repository consists of three main sections: working directorystaging area, and git repository.

The working directory holds the actual files that you’ll modify. After that, changes will be temporarily saved (indexed) in the staging area.

In the second area, you still can make further changes to your files. When you’re ready, choose the changes that you want to save (commit) permanently.

Your git repository will store the commits. You can also push the commits to the master repository so other developers can check out your modifications.

Keep in mind that Git needs a username to be associated with the commits. As such, you should create an identity through this command:

git config --global user.name "name"
git config --global user.email "email address"

Thanks to this little detail, your teammates will know who commit the changes.

Getting Git Repositories

In this part of the tutorial, you can get a git repository through two methods — turn a local directory (folder) into a git repository or clone an existing repository.

For the first method, run the pwd command to know where you currently are. The command will print the path to a local folder.

If it’s not pointing to the folder that contains your project, run the following command to change it:

cd <path of directory>

After you’re in the right directory, run the git init command, so Git can track the changes made to the files in that directory:

git init

git init will create a .git subdirectory within the local directory. This subdirectory is the one responsible for storing the snapshot of your changes.

Now, if you work on a collaborative project, you can clone the remote repository to your local machine and modify the files from there:

git clone <address of remote repository>

Indexing and Committing Changes

Let’s say you made some changes to a file named test.html. Before committing those changes, you need to put the file to the staged area by running the following command:

git add test.html

In this stage, you’re still allowed to make some alterations if you need to. Next, run this command to see whether all your changes are staged:

git status

Then, commit the file:

git commit –m “Message to go with the commit”

Afterward, type the git status command again. If it says that there’s nothing to commit, it means that all the modifications are saved.

Related  GitHub launches an Indian subsidiary to boost its developer community

If there are some mistakes in your commit message, don’t worry! You can use this command to change the latest commit message:

git commit --amend -m “updated commit message”

After you save and exit, the message will be updated.

Viewing Logs

You can study the commit history by running the git log command. It will return a list of commits made in that repository along with the author, modification date, commit ID (hash), and message of the commit.

To retrieve the commits made by a single user, you can use:

git log --author =Smith

Tagging Commits

When you’re developing a software product, there must be a time where you commit changes and want to release it as a software update. Now, it is recommended to tag that commit so you can easily identify the release point in the future.

Here’s the command to do so:

git tag -a<version-number>

By default, git tag will tag the latest commit. If you want to tag an old commit, insert the commit ID (hash) after the version number

git tag -a<version-number> <commit unique ID>

You can obtain the commit ID from the results of the git log command. However, you don’t need to copy-paste the whole hash — the first eight to ten characters are enough.

Working with Git Branches

In this section of the tutorial, you will learn how to work with git branches.

If you want to fix bugs or add a new feature, you might want to do it on branches, so the main line of development (master branch) won’t be affected when you develop that new feature.

Once the project in the branch is proven to be working, the branch will be merged with the master branch. By doing so, the master branch will have those changes, as well. We’ll talk more about merging in the next section.

To see the list of branches on your local repository, use this command:

git branch

If you want to create a new branch, just add the branch’s name:

git branch <branch name>

Now, although you’ve successfully created a new branch, you’re still in the master branch. To start modifying the new branch, you need to switch to it:

git checkout <branch name>

Don’t forget to add and commit the changes.

If you have old branches that had been merged and are not in development anymore, it’s a common practice to remove it:

git branch -d <branch name>

However, the command above will prevent you from deleting unmerged branches. Git is warning you because if it’s not merged, the master branch won’t have the changes you committed in the branch.

Force delete unmerged branches by running this command:

git branch -D <branch name>

Merging and Pushing the Branches

Merging is a way to integrate changes from another branch. So if you’ve finished creating a new feature in a branch, you need to merge this branch with the master branch so the latter can receive the changes from the former.

First thing first, you need to move to the master branch by running the git checkout command. After that, execute the git merge command:

git merge <branch name>

Once you’ve committed the changes and want to share it with your teammates, it’s time to push your commits to the remote repository.

However, before pushing the commits, you have to make sure that the command line is pointing to the right remote repository address. Check it through this command:

git remote -v

If it’s not pointing to the correct address, you need to change it:

git remote set-url origin <remote repository address>

Now you’re ready to push the commits to the remote repository:

git push origin master

That’s it! You’ll see the commits from your local repository in the remote repository.

Downloading Remote Branches

Remote branches are ones in your remote repositories. If you’re working on a collaborative project, you can say that these remote branches are the work of your colleagues.

Let’s say you cloned a remote repository and are working on a local branch. During this process, your teammates pushed their branches and made new changes to the remote repository.

Related  How to Configure FileZilla Client

Now, you want to update your working directory, so it will have the recent changes done by your teammates. To do so, you can use git pull or git fetch. However, there’s a difference between the two.

git fetch will download all remote branches and won’t affect anything in your local repository. It is a safe way to update your working directory.

On the other hand, git pull downloads the content of the remote repository and merges it with the current branch you’re working on. As a result, some conflicts might occur.

Additional Git Tutorial

Aside from everything that you’ve learned in this Git tutorial so far, there are more concepts to discover.

Merge vs. Rebase

Aside from merging, you can try rebasing to incorporate changes from a branch to the master branch. However, they’re not the same.

While merging would save all the commits from the branch in the form of a new commit, rebasing would move the commits to the top of the master branch.

Each option has its own advantages: merging won’t affect the log history, and rebasing will make the log history more linear.

However, using too much merge can make your log history unreadable as it will create plenty of new commits. Also, try not to change commits in a rebased branch to avoid conflicting code.

Git Hooks

To improve productivity, you can automate your workflow through git hooks. They are custom scripts that will enforce a specific rule before or after an event.

You can use it on events like commitmergerebase, and push. Here are some of the examples:

  • pre-commit — triggered before making a commit. For example, you can set the script to check the commit message.
  • post-commit — occurred after a commit is created. You can use it to notify the team members of a new commit.

Git Reset, Checkout, and Revert

Git allows you to undo commits and changes through one of these three commands:

  • git reset — can bring you back to one of the older commits. However, it’ll delete all the commits after that specific commit.
  • git checkout — takes your repository to the state of a particular commit. The commits after that specific commit will be considered undone, and you need to create a new branch to make any changes.
  • git revert — creates a new commit by inverting the commit you want to undo. As such, you can undo some commits without modifying the log history.

Basic GIT Commands

Here are some basic GIT commands you need to know:

  • git init will create a new local GIT repository. The following Git command will create a repository in the current directory:
git init

Alternatively, you can create a repository within a new directory by specifying the project name:

git init [project name]
  • git clone is used to copy a repository. If the repository lies on a remote server, use:
git clone [email protected]:/path/to/repository

Conversely, run the following basic Git command to copy a local repository:

git clone /path/to/repository
  • git add is used to add files to the staging area. For example, the basic Git following command will index the temp.txt file:
git add <temp.txt>
  • git commit will create a snapshot of the changes and save it to the git directory.
git commit –m “Message to go with the commit here”

Note that any committed changes won’t make their way to the remote repository.

  • git config can be used to set user-specific configuration values like email, username, file format, and so on. To illustrate, the command for setting up an email will look like this:
git config --global user.email [email protected]

The –global flag tells GIT that you’re going to use that email for all local repositories. If you want to use different emails for different repositories, use the command below:

git config --local user.email [email protected]
  • git status displays the list of changed files together with the files that are yet to be staged or committed.
  • git status
  • git push is used to send local commits to the master branch of the remote repository. Here’s the basic code structure:
    git push origin <master>

    Replace <master> with the branch where you want to push your changes.

  • git checkout creates branches and helps you to navigate between them. For example, the following basic Git command creates a new branch and automatically switches you to it:
command git checkout -b <branch-name>

To switch from one branch to another, simply use:

git checkout <branch-name>
  • git remote lets you view all remote repositories. The following command will list all connections along with their URLs:
git remote –v

To connect the local repository to a remote server, use the command below:

git remote add origin <host-or-remoteURL>

Meanwhile, the following command will delete a connection to a specified remote repository:

git remote rm <name-of-the-repository>

  • git branch will list, create, or delete branches. For instance, if you want to list all the branches present in the repository, the command should look like this:
git branch

If you want to delete a branch, use:

git branch –d <branch-name>
  • git pull merges all the changes present in the remote repository to the local working directory.
git pull
  • git merge is used to merge a branch into the active one.
git merge <branch-name>
  • git diff lists down conflicts. In order to view conflicts against the base file, use
    git diff --base <file-name>

    The following basic Git command is used to view the conflicts between branches before merging them:

    git diff <source-branch> <target-branch>

    To list down all the present conflicts, use:

    git diff
  • git tag marks specific commits.  Developers usually use it to mark release points like v1.0 and v2.0.
    git tag <insert-commitID-here>
  • git log is used to see the repository’s history by listing certain commit’s details. Running the command will get you an output that looks like this:
commit 15f4b6c44b3c8344caasdac9e4be13246e21sadw
Author: Alex Hunter <[email protected]>
Date:   Mon Oct 1 12:56:29 2016 -0600
  • git reset command will reset the index and the working directory to the last commit’s state.
git reset --hard HEAD
  • git rm can be used to remove files from the index and the working directory.
git rm filename.txt
  • git stash command will temporarily save the changes that are not ready to be committed. That way, you can go back to that project later on.
git stash
  • git show is a command  used to view information about any git object.
git show
  • git fetch allows users to fetch all objects from the remote repository that don’t currently reside in the local working directory.
git fetch origin
  • git ls-tree allows you to view a tree object along with the name, the mode of each item, and the blob’s SHA-1 value. Let’s say you want to see the HEAD, use:
git ls-tree HEAD
  • git cat-file is used to view the type and the size information of a repository object. Use the -p option along with the object’s SHA-1 value to view the information of a specific object, for example:
  • git cat-file –p d670460b4b4aece5915caf5c68d12f560a9fe3e4
  • git grep lets users search through committed trees, working directory, and staging area for specific phrases and words. To search for www.hostinger.com in all files, use:
    git grep "www.hostinger.com"
  • gitk shows the graphical interface for a local repository. Simply run:
    gitk
  • git instaweb allows you to browse your local repository in the git-web interface. For instance:
    git instaweb –httpd=webrick
  • git gc will clean unnecessary files and optimize the local repository.
    git gc
  • git archive lets users create a zip or a tar file containing the constituents of a single repository tree. For instance:
    git archive --format=tar master
  • git prune deletes objects that don’t have any incoming pointers.
git prune
  • git fsck performs an integrity check of the git file system and identifies any corrupted objects.
git fsck
  • git rebase is used to apply certain changes from one branch to another. For instance:
git rebase master

Basic shorthand command to push your repository to GitHub.

Create a new repository on the command line

echo "# new" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin   
git push -u origin master

Push an existing repository from the command line

git remote add origin <host-or-remoteURL>
git push -u origin maste

Conclusion

Git helps you manage your software development projects. Whether you work alone or in a team, this software got you covered! You can easily create new projects, copy existing projects, make new features with branches, and share those projects with your friends.

Related  How to create a Website

We hope that this tutorial is helpful for those who want to get started with Git.

If you need to learn Complete WordPress check out our WordPress Series.