Skip to content

The Practical Guide to Git

Posted on:February 8, 2021

Welcome, Developers 🖖 hope you all are doing great! Keen on having a good time?

What I have prepared for us today is kind of a little different from the previous posts. I was thinking: why not having a shorter, yet fun and interesting, post while I am preparing the second part of our series about GraphQL servers?

This is an experiment on posting quick and practical guides between the releases of the content you are already used to. We want and will keep up with the same high quality and details in our posts. The idea with initiatives like this is to publish content on a more regular basis!

Let’s get down to business, Ladies and Gentleman 💪

Table of contents

Open Table of contents

Introduction

If there is one thing that most of us developers have in common is using Git to manage different versions of an application code. I’m not gonna try coming up with any fancy definition of what Git is, it couldn’t be better than the official one:

“Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. ” - Git

It has a rich command set that enables us to handle everything when thinking about code versioning, from basic to advanced. Through Git commands, we can create new code repositories, create and manage branches, compare code between file versions, and much more. In my opinion, it’s an essential skill to have in our tool belt 🔧

Even if you have never explored much of Git before, I bet at least the git clone command you have used when cloning GitHub repos. Am I right? Regardless of your level of experience, I wish you can learn or refresh your knowledge throughout this post, guys!

I have prepared a Git command guide that I intend to be your single place to go for help in most cases when managing your Git repositories. Hope to achieve this goal 💯

I want to enforce that this is not a full documentation about all the Git commands available, neither all the variations of the commands listed below. Instead, it is what I consider to be the most commonly used and useful ones, based on my own professional experience.

In the sections below, you have the Git CLI commands with its description and examples. The idea is to make each command straightforward and simple to understand. Also, you will notice the Tags field on the commands’ description. It has the purpose of helping you when searching by the command you require at the particular moment! Let’s see how it goes, guys 👌

Environment Setup

To start, the first thing we need is to have Git installed on our machines. To download the latest version, go to the Git official page and choose the one according to your OS:

For those using macOS, I recommend using Homebrew to install it:

brew install git

Feel free to go with your preferred approach. The Git download page has the instructions you need for every OS scenario:

![Git Download]((/assets/the-practical-guide-to-git/git-download-os.png)

Once it has been installed, run the git command on your terminal, and these options should be printed in there:

git

![Git CLI]((/assets/the-practical-guide-to-git/git-cli.png)

The first checkpoint reached, guys ☑️ Time to learn about the commands that we, developers, must use!

GUI Clients

There are plenty of third-party tools available that simplifies the management of your Git repositories. Common tasks such as comparing files and versions can become a lot easier and quicker. It saves some time that could be invested in development, for example. At the end of the day, it’s a matter of personal preference. Some developers prefer to use the GUI, while others are quite used to Git commands.

If I may, I’d recommend GitKraken (free for public repos) and GitHub Desktop (free).

Alright, no more small talk I promise 🖐️

Git Commands

And the command is…

git-version

Tags: #version

Displays the installed Git version.

Usage:

git version

git-help

Tags: #help #yourbestfriend #guide

Displays help information about Git commands. It’s extremely useful when exploring commands and their parameters.

Usage:

Displays the most common commands:

git --help

Displays all commands available:

git --help --all

Displays help information about the command informed:

git --help <command>

git-config

Tags: #configuration #setup #username

Gets and sets Git configuration, such as your username, email, and much more. Uses —global to set the configuration for every repository in your local machine.

Usage:

Sets your username for a single repository:

git config user.name <username>

Sets your username for every repository on your machine:

git config --global user.name <username>

git-clone

Tags: #clone #download #copy

Clones a Git repository into a new directory on your machine. It also creates and checks out an initial branch that is forked from the cloned repository’s currently active branch.

Usage:

When [your-directory] not informed, it clones into the currenct directory:

git clone <repository-url> <your-directory>

Sets —branch in case you want it cloned with a different branch name:

git clone <repository-url> --branch <branch-name>

git-init

Tags: #initialize #reset #new

Starts an empty Git repository, or reset an existing one. Basically, it creates the .git directory on your application, which contains information about the repository.

Usage:

By default, it uses an initial branch named master:

git --init

Sets the initial branch name:

git --init -b <branch-name>

git-add

Tags: #add #stage

Adds the changed content of the current Git directory. It essentially stages the files as snapshots in the index file, so they can be committed when running the commit command.

Usage:

Stages new or modified files existed in the [path] directory:

git add <path>

Stages all new or modified files throughout the project directory:

git add --all

git-status

Tags: #status #staged #modified

Displays paths and files’ names that have been modified (updated, added, deleted) and yet pushed to the Git repository. The status of those files can change according to the stage of it, for example, not pushed to the repository, or not committed to the index file, or not staged to the working tree.

Usage:

Displays the full information about the status of the changes:

git status

Displays a short summary of the status:

git status --short

Displays the branch name and the change tracking information:

git status --branch

If you opt by visualizing the output in the short format, use the table below to interpret the status (from Git website):

X          Y     Meaning
-------------------------------------------------
          [AMD]   not updated
M         [ MD]   updated in index
A         [ MD]   added to index
D                 deleted from index
R         [ MD]   renamed in index
C         [ MD]   copied in index
[MARC]            index and work tree matches
[ MARC]     M     work tree changed since index
[ MARC]     D     deleted in work tree
[ D]        R     renamed in work tree
[ D]        C     copied in work tree
-------------------------------------------------
D           D     unmerged, both deleted
A           U     unmerged, added by us
U           D     unmerged, deleted by them
U           A     unmerged, added by them
D           U     unmerged, deleted by us
A           A     unmerged, both added
U           U     unmerged, both modified
-------------------------------------------------
?           ?     untracked
!           !     ignored
-------------------------------------------------

git-diff

Tags: #difference #comparison #changes

Show changes between the working tree (your local directory associated with a repository) and the index (staged and committed changes), changes between two trees, changes resulting from a merge, changes between two files on disk.

Usage:

git diff

I usually prefer checking for changes using a GUID, but depending on the change, the diff command does the job! The output isn’t complex to read, guys. Here’s an example:

![Git-diff]((/assets/the-practical-guide-to-git/git-diff-wd.png)

git-commit

Tags: #commit #update-index

Create a new commit containing the current contents of the index (your local repository), and the given log message describing the changes. Be mindful about this log message, not everyone in your team (or your future-self) knows exactly (or not at all) what you have changed.

Usage:

Commits only changes already staged to the index by using the git-add command:

git commit --message <message>

Stages any updated or deleted file, and also commits the changes:

git commit --all --message <message>

git-branch

Tags: #branch

Manages existing local mapped Git branches by listing, creating, or deleting branches.

Usage:

Lists existing branches (same as using —list):

git branch

Creates a new branch on the index file, and switches to the new branch:

git branch <branch-name>
git switch <branch-name>

Deletes branch if fully merged in its upstream branch:

git branch --delete <branch-name>

Forces the deletion of the branch, same as using —delete —force:

git branch -D <branch-name>

git-checkout

Tags: #restore #switch-branch

Switch branches, restore working tree files, and also can be used to create new branches. Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, it will also update HEAD to set the specified branch as the current branch.

Usage:

Switches to the new branch, only if current branch does not has local changes not updated to the index file (committed or stashed):

git checkout <branch-name>

Switches to the new branch, and throw away any existing local change:

git checkout --force <branch-name>

Creates a new branch, and switches to it. If already exists a branch with the same name, it throws an error:

git checkout -b <branch-name>

Creates a new branch, and switches to it. By using -B, if already exists a branch with the same name, it then resets it to the start point:

git checkout -B <branch-name>

Reverses the modifications of an unstaged file:

git checkout <file-name>

git-switch

Tags: #switch-branch #create-branch #new

Switch branches, and create new ones as well. Similar to the checkout in regards to performing those operations. Basically, the checkout command can do what the switch command does, and more.

Usage:

Switches to another branch:

git switch <branch-name>

Creates a new branch and switches to it:

git switch -c <new-branch-name>

Creates a new branch and switches to it, resetting in case the new branch name exists:

git switch -C <new-branch-name>

Switches to another branch, merging any existing local modifications:

git switch -m <branch-name>

git-fetch

Tags: #download #update-remote #refresh

Download objects and refs from another repository. It does not merge the downloaded changes into your current repository. Think of this as a way to update your remote-tracking branches with their latest changes, and not affecting your local version.

Usage:

It fetches all branches from the origin (or informed remote repository):

git fetch origin // or <remote-repository>

It fetches a specific branch from origin (or informed remote repository):

git fetch <remote-repository> <branch-name>

It fetches all branches from all registered remote repositories:

git fetch --all

git-pull

Tags: #update #get-latest-version #merge

Fetch from and integrate with another repository or a local branch. It also merges the version coming from the origin, with the current branch.

Do you remember the fetch and merge commands we have just seen? That’s exactly what pull consists of. Under the hood, when we run the pull command, what happens is:

git fetch
git merge

When getting updates from another repo, some version conflicts can happen. By default, the pull command does not commit the merged changes so you have the chance to verify and resolve the merge conflicts.

Usage:

Pulls the latest version from the origin and merge into the current branch:

git pull

Pulls the latest version from the informed branch and merge into the current branch:

git pull origin <branch-name>

git-push

Tags: #submit #apply

Pushes local changes to a remote repository. It applies the content of the index file back to the remote repository or origin.

Usage:

Pushes the changes to the origin (or configured upstream). The origin argument is optional:

git push origin

Pushes the changes, and sets the upstream or tracking reference:

git push --set-upstream origin <branch-name>

Pushes the changes to a specific remote repository:

git push <remote-repository>

git stash

Tags: #save-temp #reserve

Saves the current state of the working directory and the index (local modifications), and reverts back to a clean working directory (your last commit stage).

By default, a stash entry has the naming convention of WIP on branchname branch-name. However, when creating a new stashed record, you can inform a message that better describe your changes.

Usage:

Creates a stash entry based on the current local changes:

git stash push

List the existing stash entries. It shows the branch name and a short description of the commit it was based on:

git stash list

Shows the changes stashed on stash entry:

git stash show '<stash-name>'

Removes a single stash entry from the list, and apply the changes to the current working tree:

git stash pop

git-rm

Tags: #remove #delete

Removes files from the working tree and from the index. If you run git status after applying the remove command, you will see the deleted status of the file removed. If you push it to the remote repository, the file will be also deleted there.

Usage:

Remove file from working tree and from the index:

git rm <file-path>

Force to remove the file, even if it has been modified and not yet pushed to the index:

git rm -f <file-path>

Recursive remove files in the informed folder.

git rm -r <folder-path>

git-restore

Tags: #restore #undo

Restore working tree files to the current index version. It basically undoes modified files in the working tree.

Usage:

Undo a modified file:

git restore <file-name>

Undo modified files in the folder:

git restore <folder-name>

Undo all modified files in the repository:

git restore :/

git-blame

Tags: #revision #history #author #versions

Displays the change history of a specific file.

Usage:

git blame <file-path>

git-log

Tags: #commit-logs #history

Shows the commit logs.

Usage:

Shows all the commits:

git log

Good example. Shows the commits that are applied to your local branches, but not to the remote repository branches:

git log --branches --not --remotes=origin

Next Steps

Please have in mind that this guide was built based only on the Git commands that I use often at work and at my studies. If you want to go deeper and learn more commands, and more options for the commands I showed today, the official Git documentation is the best place to go!

Guys, I have to admit it’s hard not to get too excited and start creating a new app together with you so we can practice the commands we have seen here today 🤖 I’m afraid it would miss the point of this post being a guide only.

But you know what, what about we continue this journey on the next post, then? We have the second part of our series about GraphQL API servers just around the corner. Then, the next content will be about using GitHub to manage the code of a React application 👊 How does it sound?

Useful Resources

Conclusion

Be proficient at Git commands gives you the flexibility and control you need when managing your application repositories. You do not have to know all of them on top of your head, not at all. The thing is: what does help you is to know how to search and find what you need, by using the git help command, the official documentation, or in a guide like the one I have prepared for us today.

As I always like to say: thank you very much for taking the time to read this post, developer! I wish you have learned something that will contribute positively to your journey ✌️

Did I miss any Git command you use often in your day-to-day studies/work? Is there any other command you want to suggest? Leave a comment below and let’s learn together!

Keep moving forward, everyone 🚀 one step at a time!

Follow Us

The Welcome, Developer has a LinkedIn page! If you enjoy our content, we would be very happy to have you as our follower! In there, we will update you about new posts, new projects, and all the cool stuff!