Basic git commands with examples

Basic git commands with examples

In this article, I will tell you what are the widely used basic git commands with examples.

Even more! I will share the best practices to use the basic git commands with examples.

Do not worry if you are a newbie. You would be expert after completing this 3 step course.

If you do not know at all about version control system then first read What is version control system – a step by step guide for Git (part 1 out of 3) and then come back here to continue to be expert in GIT.

I divided the complete git tutorial into 3 parts and this is the second chapter, you can download the full version of git tutorial pdf if you want to study it offline.

Create a central repository – It’s called remote repository

Central repository – while you are working in a team, You will need to have a central location where all of your team members can update their code and all can take the updated code from central repository to their local working directory.

You can have a central repository on your own server but I would recommend using the existing repository hosting websites which provide the service to host the central repository.

Some of the popular central repository hosts are GitHub, GitLab, and Bitbucket.

I will use GitHub for this article.

Before going to the next section, I assume you already created an account on GitHub.

Login into the GitHub and create a central repository.create github new repository

In next step select “Initialize this repository with README”, so your first file in GitHub repo will be a readme.md file.

create github repo 2

Once you added the Readme file notice how the commit comes in the list – well, if it is early to understand the commit, then wait until we reach on git commit command section in this tutorial.

Install the GIT on your local system

You can find the step by step guide to know how to install git on Window or Linux or Mac from this link.

You now have your central repo, installed the git on your local system.

If you run git command without installing, you would receive the error message git is not recognized as an internal or external command”

git commands list

Let’s start learning git commands with examples before start working on central repo.

  1. The list of commonly used basic git commands
  2. git clone – clone the remote repository to your local directory
  3. git init – initialize a git repository in existing directory
  4. git status – see the status of your local repository
  5. git add – add a local updated/added files to git stage
  6. git commit – commit all staged files to git repo with commit hash id and revision history
  7. git rm – remove a file from a git repo
  8. git push – push the local commits to the remote repo
  9. git pull – pull the changes from the remote repo to your local repo
  10. git remote add – add your updated file directly to the remote repo
  11. git branch – display all local branches, the current working branch will be denoted by an asterisk
  12. git checkout – Switch one branch to another branch or create a new branch
  13. git merge – merge changes of one branch to another branch
  14. git stash – put your incomplete code in another stage so you can switch the branch without commit.
  15. git log – show the commit history
  16. git config – change setting of the git repo
  17. git reset – reset your repo to old commit has id
  18. git rebase – you can combine or move the commits into a new base commit.
  19. gitignore – gitignore is not a command, it’s a file where we specify what files and directory git must not track.

git clone command– copy remote repository to your local directory

Ok, you have created the central repo.

You have a basic idea about git commands list.

Now its time to get this on your local system to start working.

You will find a URL on GitHub to clone the central repo to your local directory.

find url to clone github repo

git clone command used to copy the remote repository to your local directory.

git clone {repository url}

git clone command

That will copy all files from central repo to your local directory. By default, git clone creates a subdirectory and initialize it as git repository. You can tell git to not create the subdirectory.

Clone remote repo without subdirectory

If you noticed, this clone created a subdirectory (subdirectory is the name of central repo) in your existing folder. If you do not want to create subdirectory into your local directory on git clone then use the command given below.

git clone {URL} .
//notice the period "." in the end

This command will clone the content from the central repo without the folder of the repository.

You can invite your colleagues to work on this repo from GitHub dashboard and, he then needs to clone the repo in his local directory.

What is .git directory?

After cloning the central repo, if you see your directory then you will see there is a new directory created named .git. If you are not able to see this then make sure you have “view hidden files” enabled in folder options of your computer.

I will not go in the more detail what it has, in simple language, it is a database that contents all required metadata (configuration, all your changes, version history, logs and, all information) that require for git to do version control.

That’s the reason it called DVCS, every user would have all files on their own local and .git contain all commit/changes in the local repo.

The programmer can push the commits to the central repo and can pull the latest updates from central repo to their local repository.

We will learn it later in this article how to push commits on central repo and how to pull the latest updates from the central repo to the local directory and what problems we can face in pull and push the commits.

Stay tuned!

git init command- create an empty git repository or initialize an existing directory as a git repo

Use case 1: I am starting a project and did not create a central repo yet. While you clone the central repo, it will automatically initialize the git in your local directory and create the .git folder.

But what if you do not want to create the central repo, but want to work on git locally.

You can create a directory and then use git init command to make your directory a local git repository.

cd git-tutorial
git init

Use case 2: clone a remote repository into a working local directory – You are working on a project and after a couple of weeks or months you realize that you should use version control system and a central repository also so another developer can participate in code.

We will do this in 3 parts:

1. initialize git in the local directory and will make file trackable
2. add a remote repository to the local directory
3. push all files to the remote repository

Initialize your local directory for git repo

git init

Make your all files trackable. Git does not store version of all files it will maintain version history for those files which you would tell him to do.

To make a file trackable you would need to use git add and git commit command.

git add .git commit -m “First commit”

//git add . will add all your files into git staging area//git commit will commit the staged changes and give a unique commit id

We will read about git add and git commit below in this article.

Add remote repository to local directory

git init
git remote add origin {remote repository URL}

What is difference between git init and git clone

git init command initializes the local directory into a local git repository.

git clone command first initializes the local directory into a local git repository and then copy content from the remote repository into it.

git status command – check the status of local repository

You are making changes in many of the files and then forget which files you made changes.

Don’t worry, use git status command to know what files are added or modified.

git status

git status command

If you look the above image git status shows how many files are modified files and how many are newly added(untracked files). Untracked files are those files which I added in my folder but never staged these in git repository. I have to use git add command to add these files into git staged area.

git add command – add new file or modifed file into git stage area

The stage is a middle container between your code(working directory) and .git directory(repository).

Before sending the changes to a git repository, first you have to add these files in the staged area and then you need to move the staged file into the git repository.

Sounds complicated?

Let’s take an example:

Let’s say you are working on two features of a project, one feature is completed and another is partially done. Its end of the day and you have to go home. You do not want to commit the partially done task so first add all files into the staging area (use git add filename) which are related to task one only and then commit these staged files to git repo using git commit -m “completed task one”.

Then, add files into the staging area which you updated for task second and do not commit it. Keep working on these when you back tomorrow and commit once this task is completed.

Every time when you do change in a file, it must be added first in the staging area.

Options for git add command

Option Description
git add First, run the git status and see what files are added or modified. Then you can add these to the staging area by git add command.
git add {filename1}, {filename2}, {filename3} Again first run the git status to know what files are added or modified, then you can use git add command and specify multiple files separating them by a comma.
git add –A It will stage all files which are newly added or modified or deleted.
git add . It will stage new and modified, it will not stage deleted file.
git add -u It will stage modified and deleted but will not stage new file.

git add command

git commit command – commit files from staging area to git repository

You already saw the commit words multiple times in this article. So you might get a sense what is the use of it.

git commit command basically takes your changes from staging area and record these in the local git repository. Every commit assigned by a unique commit SHA-1 hash.

The commit id is a 40 digit long sha-1 hash encrypted string.

Git commit id example: b783896cd2c024e59fc2c101e489b4fa9ab7f5ec

Commit can be identified by this long 40 digit string or can be identified by short version(first few chars 5 to 8 of hash string)

By using this commit hash you can revert on that particular commit or can take selective commits from history to recover old code. I will discuss later in this article on that.

git commit -m "backend validation on product add form is completed"

Options for git commit command

git commit -m {message}

When you are committing a task to the git repo, make sure you write a descriptive message so later you or your colleagues can understand what is this commit about.

git commit -a or git commit –all

That does add and commit both altogether, it will take all modified or deleted file and then first add those in the staging area and then commit to git repo.

Special note: It will not do anything with the newly added file.

git commit –amend
It used to change the most recent commit.

–amend use case 1: after the commit, you realized that you should write more text in the description to describe your commit.

Don’t worry, you can reopen the most recent commit to update that.

You can use git commit –amend to open the most recent commit. You need to make sure that the staging area does not have any file otherwise that also will be added in your commit.

–amend use case 2: Sometimes you find the mistakes in your code after committing. Lest say I commit a task which validates product form inputs. Later I realize a bug or found missed one more validation. The thumb rule is you should have one commit for a task so instead of creating a new commit for missing validation I would amend the most recent commit which I have for validation task.

Change the files to add missing validation, add these files into the staging area by using git add command. And then use git commit –amend to open the most recent commit. Update the commit message and hit enter.

That will add the newly staged file into the commit and will update the commit message if you change that.

Best practices for git commit command

# Test your code before you commit
Make a practice to not commit the incomplete task, make sure it is tested so a commit represents a complete task and does not have any side effect on other modules. Your commit is going to be pushed into the remote branch so it becomes more important when it goes to others.

# Commit as often as you can and keep it small
Making sure code is tested and committing often can be contradictory but you must plan your task in such way that both can be possible. You will have to divide your module into small independent tasks which will not have the side effect on another existing module. As soon as your small task completed you can commit that and can push on remote repo so others can pull in their local repo. That way it will be easier for everyone to fetch your changes into their local repository without or with minimum merge conflicts.

# Commit should have related things
You should not mix up the different tasks into a single commit. It makes commit understandable. Other programmer or reviewer can easily understand and can make it easy to roll back if something went wrong. If there are two bugs reported then you should create two separate commits.

# Write a good commit message
Writing a good message with commit is a most important task of the version history, that make version history human readable. You must write the message which tells a complete detail about the commit so even you open the commit after months, you or any other programmer can understand the commit easily.

10 rules to write a good commit message

I am not the maker of these rules, you can find these already here.

  1. Start with a subject line: how you make a subject for email, we try to convince the reader to tell what is the email about.
  2. Similarly here, make a subject line relevant to your commit so it gives an overview of your commit
  3. Keep it short – less than 50 charsDo not end subject with period “.”
  4. Keep a blank line after the subject
  5. Capitalize the subject line
  6. Use the imperative mood in subject
  7. Wrap the body at 72 chars
  8. Use the body to answer what, why and, how
  9. If needed give reference to another tool like reference id from issue tracker or task management tool etc.
  10. Write the reference at the bottom of the message.
Write subject line in 50 chars or less

More detailed explanatory text, if necessary. Wrap it to
about 72 characters or so. In some contexts, the first
line is treated as the subject of an email and the rest of
the text as the body. The blank line separating the
summary from the body is critical (unless you omit the body
entirely); tools like rebase can get confused if you run
the two together.

More text here to explain what, why and, how. You can 
write detail one or more paragaraph to explain what 
the probelm you are solving in this commit and how 
you solved this.

Further paragraphs come after blank lines.

- Bullet points are okay, too

- Typically a hyphen or asterisk is used for the bullet,
preceded by a single space, with blank lines in
between, but conventions vary here

You can mention the reference number if you are using
any task management tool or issue tracker.

Task# 987
Issue#: #123, #876

Wrapping it up

So now, you must understand about version control and basic commands of git. You can start working with the git.

If you have any questions, suggestion or correction, feel free to comment below–I will be more than happy to answer and learn.

I am preparing next article about git advance topics. Meanwhile, if you have any question or suggestion just let me know in comments, I will be more than happy to learn or answer.