The Ultimate Git Guide for Beginners

Complete Guide to Git Command Line

What Do I Need?

  • Any Dedicated or Virtual Server.
  • Ubuntu.
  • Terminal.
  • Git.

What is Git?

One of the most popular source control systems available, Git has been around for a very long time. Git is a completely mature and actively maintained open-source project originally developed by Linus Torvalds in 2005. Who is Linus Torvalds? Only the world-famous creator of the Linux operating system kernel. A simply monumental amount of software projects rely on Git for version control. The beauty of Git is it’s a decentralized approach to version control. Having a distributed architecture, it’s an example of a distributed version control system or DVCS. Instead of only having one place for the full version history of the software as is popularly prescribed with once-popular version control systems like CVS or Subversion, or SVN, in Git, every developer’s working copy of the code is also a repository that can contain the full history of all the submitted changes.

One of the best features of Git is that it’s been designed with security and integrity in mind. The content of the files as well as their true relationships between files and directories, versions, tags, and commits, all these objects in the Git repository are secured with a cryptographically secure hashing algorithm called SHA1. This ensures the protection of the code and the change history against both accidental and malicious change and also ensures that the history is fully traceable. With Git, you can be sure you have an authentic content history of your source code.

If you want to start using Git, you need to know where to host your files, or your repositories. A repository, or repo for short, is a project that contains multiple files. In your case, a repository will normally contain code-based and other files. There are two ways you can host your repositories. One is online, on the cloud using GitHub or GitLab, and the second is offline, set up on your local machine. There are three popular Git online hosting services:

A lot of open-source projects use GitHub to manage their projects. Using GitHub is now free, even for teams, since the take over by Microsoft, even if your project isn’t open-source. It includes an area for a wiki and issue tracker, that makes it easy to include more in-depth, detailed documentation and gets developer and user feedback. If you want to contribute, you just fork, or get a copy, a project, make your changes, and then send the project a pull request using Github’s super easy web interface. A pull request is your way of telling the project that you’re ready for them to review your changes. One of the biggest advantages to GitHub, is that it can directly integrate into common platforms, such as Amazon and Google Cloud, with services such as Code Climate to track your feedback. It can also highlight syntax in over 200 different programming languages.

    1. The Three Phases of Git

To understand your essential workflow in layman’s terms, Git has a working/development environment, a staging environment, and the production-quality code or the central repository.
Complete Guide to Git Command Line

  1. A Recommended WorkFlow
    1. Different developers and teams like to use different strategies in order to manage Git effectively. Here is a strategy that I’ve used on many teams and even my own commercial development projects. It’s similar to workflows on many big and small projects as well.
    2. I only have two permanent branches:
      master
      development
    3. When a new issue arises, or a new feature is implemented there are two main approaches:
      1. If the feature or issue is a quick one:
        the commits you’ll make won’t break the code, at least theoretically, you can commit to development or create a quick feature branch, and then merge it to development.
      2. If the feature or issue will take more than one commit to finalize:
        maybe it will take a couple of days of commits before a feature is finished and it gets stable again, you create a feature branch and then merge it to the development branch once ready.
      3. If the feature or issue is a hotfix:
        if something on your production server requires immediate action, like a bugfix, you’ll need to get it solved asap, you create a short hotfix branch, deploy the feature or fix the issue, test the branch locally, test the branch on a test machine, merge the hotfix branch to the master and development branches.
      4. If development is unstable:
        the development branch will always be in a state of flux, that’s why it should be put on a ‘freeze’ when preparing a release, the code is tested and every workflow is checked in order to verify the code quality, and it’s then prepared for merge to the master branch.
      5. Master is the latest stable release:
        every time the development branch or feature or hotfix branches are merged into the master branch, you should tag it with a version number, and if on Github you should also create a release tag, so that it’s easy to move back to a previous state if something goes wrong.
  1. How to Install Git
    Installing Git is comparatively easy on all platforms:

    1. OSX
      Using Homebrew, use the following command:

      brew install git
    1. Windows
      Download and install Git for Windows.
    1. Linux
      Use the package manager of your distribution to install Git, using the following commands:

      sudo apt-get install git

      or

      sudo yum install git
  1. Working with GitHub Online
    1. One of the easiest ways to get started with the creation of your repository is to use Github.com. Once set up on that website you’ll be able to clone the newly created repository to your local machine, work on your project and then push it back easily.
    2. Create a new repository by clicking the New Repository button on the GitHub website:
      What is Git?
    3. Pick a sensible name for your first repository, add a small description, check the Initialize this repository with a README’ checkbox, and click the Create repository button:
      What is Git?
    4. Congratulations, you’ve created your first GitHub repository. Next copy the repository on your local machine. To do that, you’ll need to clone the repository.
    5. To clone a repository means that you’re taking a repository that’s on the server and cloning it to your local machine, just like downloading it. On the repository page, you need to get this https address:
      What is Git?
    6. Once you have copied the address of the repository, you’ll need to use your terminal. Use the following command:
      git clone {github-repository-url}

      What is Git?

    7. That common will make a copy of the repository on your local machine.
  1. The GitHub WorkFlow
    The GitHub workflow is a lightweight, branch-based workflow built around core Git commands used by teams around the globe—including ours. The GitHub flow has six steps, each with distinct benefits when implemented:

    1. Create a branch: Topic branches created from the canonical deployment branch, usually main or master, allow teams to contribute to many parallel efforts. Short-lived topic branches, in particular, keep teams focused and result in quick ships.
    1. Add commits: Snapshots of development efforts within a branch create safe, revertible points in the project’s history.
    1. Open a pull request: Pull requests publicize a project’s ongoing efforts and set the tone for a transparent development process.
    1. Discuss and review code: Teams participate in code reviews by commenting, testing, and reviewing open pull requests. Code review is at the core of an open and participatory culture.
    1. Merge: Upon clicking merge, GitHub automatically performs the equivalent of a local ‘git merge’ operation. GitHub also keeps the entire branch development history on the merged pull request.
    1. Deploy: Teams can choose the best release cycles or incorporate continuous integration tools and operate with the assurance that code on the deployment branch has gone through a robust workflow.
  1. First Time Setup
    1. Now that you have Git on your system, you’ll want to do a few things to customize your Git environment. You should have to do these things only once on any given computer; they’ll stick around between upgrades. You can also change them at any time by running through the commands again. Git comes with a tool called git config that lets you get and set configuration variables that control all aspects of how Git looks and operates. These variables can be stored in three different places:
      1. [path]/etc/gitconfig file: Contains values applied to every user on the system and all their repositories. If you pass the option --system to git config, it reads and writes from this file specifically. Because this is a system configuration file, you would need administrative or superuser privilege to make changes to it.
      1. ~/.gitconfig or ~/.config/git/config file: Values specific personally to you, the user. You can make Git read and write to this file specifically by passing the --global option, and this affects all of the repositories you work with on your system.
      1. config file in the Git directory (that is, .git/config) of whatever repository you’re currently using: Specific to that single repository. You can force Git to read from and write to this file with the --local option, but that is in fact the default. Unsurprisingly, you need to be located somewhere in a Git repository for this option to work properly.
    1. Each level overrides values in the previous level, so values in .git/config trump those in [path]/etc/gitconfig.
    1. On Windows systems, Git looks for the .gitconfig file in the $HOME directory, C:\Users\$USER for most people. It also still looks for [path]/etc/gitconfig, although it’s relative to the MSys root, which is wherever you decide to install Git on your Windows system when you run the installer. If you are using version 2.x or later of Git for Windows, there is also a system-level config file at C:\Documents and Settings\All Users\Application Data\Git\config on Windows XP, and in C:\ProgramData\Git\config on Windows Vista and newer. This config file can only be changed by git config -f  as an admin.
    1. You can view all of your settings and where they are coming from using:
      git config --list --show-origin
  1. Your Identity on Git
    1. The first thing you should do when you install Git is to set your user name and email address. This is important because every Git commit uses this information, and it’s immutably baked into the commits you start creating:
      git config --global user.name "John Doe"
      git config --global user.email johndoe@example.com
    2. Again, you need to do this only once if you pass the --global option, because then Git will always use that information for anything you do on that system. If you want to override this with a different name or email address for specific projects, you can run the command without the --global option when you’re in that project.
  1. Your Editor
    1. Now that your identity is set up, you can configure the default text editor that will be used when Git needs you to type in a message. If not configured, Git uses your system’s default editor.
    2. If you want to use a different text editor, such as Nano, you can use the following command:
      git config --global core.editor nano
    3. On a Windows system, if you want to use a different text editor, you must specify the full path to its executable file. This can be different depending on how your editor is packaged. In the case of Notepad++, a popular programming editor, you are likely to want to use the 32-bit version, since at the time of writing the 64-bit version doesn’t support all plug-ins. If you are on a 32-bit Windows system, or you have a 64-bit editor on a 64-bit system, you’ll type something like this:
      git config --global core.editor "'C:/Program 
      Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
  1. How to Initialize a New Repository
    1. Create a clean folder/directory on your system. Personally, I’d recommend doing this directly onto whatever external device you’re packing as this ensures that your development codebase is as mobile as possible. If doing things this way ensure that the drive is fully encrypted.
    1. Once you’ve installed Git on your system, you’re able to access it immediately by using the following command:
      git

      What is Git?

    1. In your clean folder using the following command in order to initialize your repository:
      git init

      What is Git?

      1. The git command creates a .git folder at the location where you’ve run the command. If you don’t see it, it’s because it’s a hidden folder. I’d recommend enabling hidden files and directories in your operating system in order to show this and other hidden folders.
      1. Anything related to your Git in your newly created repository will be stored in this .git directory. Everything except the .gitignore file.
  1. How to Add Files to a Repository
    1. Your life will always be easier if you start your new repository with the standard README.txt file
    1. Use the following command to a new text file to your directory:
      echo "There is no spoon." > README.txt

      What is Git?

    1. The new text file is now in your directory, but Git wasn’t told to add it to its index.
    1. Use the following command in order to check what files have or haven’t been added to its index:
      git status

      What is Git?

  1. Add Files to the Staging Area
    1. In order to make it visible to Git and put it into your staging area use the following command:
      git add README.txt

      What is Git?

    1. Once a file is in your staging area, you should remove it by using the following command:
      git reset README.txt

      What is Git?

  1. How to Commit Changes
    1. Once you’ve made one or more changes to your staging area, you should commit them by using the following command:
      git commit -am "Description of your change(s)"

      What is Git?

    1. Now, clean the status of the staging area using the following command:
      git status

      What is Git?

    1. At this point I’d recommend checking that you’ve successfully permanently stored the edits you’ve made into the record store, which you can inspect using the following command:
      git log

      What is Git?

  1. All About Branches
    1. When you commit a file to Git, you’re committing it into the current branch. Git allows you to work simultaneously on multiple, separate branches, different lines of development which represent forks of the main branch. Git is super flexible. You can have an infinite number of branches active at the same time, and they can be developed independently until you want to merge one of them into another.
    1. Git by default creates a branch named master. It’s not particularly special in any way other than it’s the initial, or first, one created.
    1. Now, let’s create a new branch called develop by using the following command:
      git checkout -b develop

      What is Git?

    1. The git branch command lists all the branches the repository has.
      What is Git?
    1. When creating the new branch, that branch points to the latest commit made on the current branch. If you switch to it, using git checkout develop, and run git log, you’ll see the same log as the branch that you were previously.
  1. Git Life is About Push and Pull
    1. In Git, you always commit locally. This is one of the most awesome benefits over SVN or CSV, where all commits had to be immediately pushed to a server. You work offline, do as many commits as you want, and once you’re ready, you can push them to the server. This is so that your team members, or the community if you’re pushing to GitHub, can access your latest and greatest code in development.
    1. If you have an existing repository on GitHub or GitLab, you can publish it. The procedure involves creating a repository on the platform, through their web interface, then you add that repository as a remote, and you push your code there.
    1. In order to add a remote use the following command:
      git remote add origin https://github.com/your/reponame.git
    1. The alternative approach preferred by many is creating a blank repository on GitHub or GitLab and cloning it locally, in which case the remote is automatically added for you.
    1. Once you’re done with your changes, at least for the moment, you can push your code to the remote, using the following command:
      git push origin master
    1. You specify origin as the remote because you can technically have more than one remote. That is the name we added previously, and it’s a convention.
    1. The same sort of syntax applies to pulling, or retrieving files, using the following command:
      git pull origin master
    1. This command tells Git to pull the master branch from origin, and merge it into the current branch.
  1. Time to Branch, Merge and Rebase
    1. Parallel development ideology consists of:
      branching,
      merging, and
      rebasing.
    1. Create a new branch on your demo repo using the following command:
      git branch new-branch

      What is Git?

    1. In order to select that new branch you’ll need to check it out using the following command:
      git checkout new-branch

      What is Git?

    1. Use this command to check that the appropriate branch is now selected:
      git branch
    1. Now that we’ve got our new branch selected we can practice merging it with the master branch. The use case for this kind of methodology would be when you’ve been making alterations to a piece of code in development.
    1. The git merge command lets you take the independent lines of development created by git branch and integrate into a single branch:
      git merge new-branch

      What is Git?

    1. There’s an alternative way to merge branches to the master branch. It’s called rebase. This is infinitely more efficient as it’s used to make a linear sequence of commits. It’s also used for cleaner project history and reduces the number of branches.
      git rebase new-branch

      What is Git?

    1. Always make sure to create files, add them and commit them in order for the change to take place and keep your code error-free and running.
  1. SSH Keys
    1. To push the code from the local repository to your remote repository we first need to authenticate. To do that we need an SSH Key. Github uses SHA-1 Algorithm for secure hash which generates a 40-digit hexadecimal code.
    1. Use the following command in order to generate a key:
      ssh-keygen

      What is Git?

    1. To generate the ssh key use the following command:
      cat 'path' // usually id_rsa.pub where the public key is saved
    1. To check whether or not you’ve successfully authenticated use the following command:
      ssh -T username@github.com
    1. A message will pop up saying you’ve successfully authenticated yourself. Once your ssh key has been generated you’re good to go to start pushing code from your local repository to the remote repository.
  1. Conflicts and Resolution
    1. In both push sending files to a single or multi-branch repository, or pull retrieving files from a single or multi-branch repository, there is an ever-present problem to consider and mitigate: if the .git contains changes incomparable with your set of commits, the operation will fail. This happens when the contains changes subsequent to your latest pull, which affects lines of code you worked on as well.
    1. In the case of push, this is usually solved by pulling changes, analyzing the conflicts, and then making a new commit that solves them.
    1. In the case of pull, your working copy will automatically be edited with the conflicting changes, and you need to solve them, and make a new commit so that the codebase now includes the problematic changes that were made on the remote.
  1. Command Line vs Graphical Interface
    1. Initially, we discussed primarily command line Git application. This was necessary in order to show you how Git actually functions. However, in the day-to-day operations, you’re most likely to use an app that exposes you to those commands via a nice UI, although many old school developers will espouse a GUI for the command line any day.
    1. That considered, there are many awesome applications that are made to simplify the life of a developer that turns out very useful, especially when you dive even more into the complexity of a Git repository.
      1. GitHub Desktop
        1. https://desktop.github.com/
        1. Free and currently only available on Windows and Mac.
      1. Tower
        1. https://www.git-tower.com/windows
        1. Paid and currently only available on Windows and Mac.
      1. GitKraken
        1. https://www.gitkraken.com/
        1. Free/Paid and available on Windows, Mac and Linux.

Conclusion

Git as a technology platform is freaking amazing and permits some really awesome tricks of data storage. One of the many things I’d recommend exploring is deploying an on-premises Git server on a Raspberry Pi 4, using the amazing hardware and awesome software you can build something truly efficient and incredibly useful.

JB Benjamin
Author:
Extremely technically proficient and a highly motivated Digital Content Designer responsible for the development of multiple successful digital campaigns for several international companies and agencies.

Share this post

"The Ultimate Git Guide for Beginners"

The Ultimate Git Guide for Beginners