25 Git commands that every developer should know

Simona Djagaduroska
Netcetera Tech Blog
15 min readNov 21, 2018

--

Nowadays, an average working day of a developer cannot pass without using Git. Yes, Git has become an important part of our everyday development process and it helps us a lot when working with multiple people.

To be able to use it efficiently and get most of it, one should understand the way it works behind and gets familiar with. If you are new to Git, what you probably do is searching the web for answers (like “How to put the changes from the last two commits into one and keep the message of the first one?” or “How do I redo a reverted commit?”) and copy-paste them without understanding what they do and when should be used, which is not the best thing to do (I did the same though 😌).

So, in this article, I will explain the commands that IMO are a must for every developer and are used quite often. I will not explain how Git works and I assume that you have some basic knowledge about Git.

Setting up

1.init
You have just created a project in your favorite IDE and the next step is to set up the git repository. What you should do is very simple — you just need to tell Git which directory should be used and run git init .

git init

Yes, go to the directory that contains your project files and run git init. That’s it! Git will create a hidden .git directory and use it for keeping its files organized in other subdirectories.

2. config
After creating your repository you might want to configure some basic things in it, like setting your username. That’s why the config command exists.
You can set your username simply by running:
git config user.name=<replace_with_your_username>
or your email by running:
git config user.email=<replace_with_your_email>
This will set the username in your local repository, but note that later if you create another repository you will need to set up your user information once again. You can avoid this by adding the global option in the command which will globally set your information:
git config --global user.name=<replace_with_your_username>

You can use config to configure other things e.g to get more magenta color in your output:
git config --global color.status added "magenta dim" 😆 This can also be configured in the configuration file:

[color "status"]
added = magenta dim

3. clone
But, how do you get a remote repository on your computer?
You do it with thegit clone command and just pass the URL as a parameter. The command will clone the whole remote repository into your machine.

4. alias
With alias you can create shortcuts to your favorite commands. It is a very powerful tool which helps you wrap a sequence of commands and save them under some name. Alias is not a standalone command and it is used together with the config command. So, if you want to save some command under another shorter name you can use: git config --global alias.<new_name> <git_commands>
Here is an example:

cherry-pick alias

You can also add the aliases directly in the config file, so the command in the example can be translated into the following configuration in the global configuration file:

[alias]
cpick = cherry-pick

Doing and undoing changes

5. status
You worked a while on your task and you want to save your changes. What do you do at this moment? Might be useful to first run the git status command and get an overview about the status of your repository.
The command will print out some useful information like the name of the branch that you are currently working on, the number of commits that your branch is behind/ahead of its remote and the new/modified files grouped in three lists:
1. Changes to be committed
2. Changes not staged to commit
3. Untracked files

git status output

6. add
Before you commit your new or modified file, it should be added to the staging area. You do it by running the git add command and pass the name of the file (or name of the directory) as a parameter.
To add all of the files use git add .

7. rm
To remove files we use git rm. If you have a file in the staging area and you don’t want to include it into your commit just run
git rm --cached <replace_with_the_path_of_your_file> , and your file will be removed from the “Changes to be committed” list.

8. commit
Your task is finished and you want to save your changes. What do you do now?
After you had a look at your “Changes to be committed” list to ensure that all of the necessary files are staged, you run git commit. After you execute the command, your default editor will open and you should enter the commit message.
If your message is short, it might be easier to include the message in the git commit command like:
git commit -m “Your_commit_message”
You can also add the -a option so that Git looks at your working tree and performs git add for the new/modified files and git rm for the deleted files before the commit.

An interesting option that can be used is the amend option. With the ammend option Git lets us take the last commit and do some changes to it.
Actually, amend will not modify the last commit, but create a new one and replace the old one with the new one. One common scenario to use the amend option is when you want to change the commit message:
git commit --amend -m “<your_new_commit_message>”

Fixing typo with amend

Another common scenario is when you forgot to add a file to your commit and you don’t want to create another commit for that particular file only.
Important to note here is that the public commits should not be amended. It might easily happen that your colleagues have based their work on that commit and you don’t want your colleagues to get into a confusing situation.😊

9. checkout
Git checkout operates upon different entities like files, commits and branches and allows you to navigate between them. If you want to switch to existing branch you can use:
git checkout <name_of_the_branch>, or if the branch is not yet created you can add the -b argument like git checkout -b <name_of_the_new_branch> and Git will create and new branch with the given name and immediately switch to it.
To switch to specific commit use: git checkout <commit_id>

git checkout

As you can see in the screenshot, Git prints out a nice little note that you are in a “detached HEAD” state and what you can do in that state. To get out of the “detached HEAD” state simply checkout the branch that you were on (or it can be another branch).

10. reset
Git reset is a very useful and powerful command that helps you to undo changes. There are different ways to use it, but the most common one is with providing the mode and the commit id as arguments.
git reset <mode> <commit>
There are three modes of reset and in order to understand them, you have to be familiar with the three trees of Git. If you are not then here is one nice tutorial.

Mixed
The default invocation of git reset will use the mixed option and HEAD as commit id. It will reset the ref pointers and move the changes from the staging index to the working directory. In that way, the staging index will match the state of the commit that was specified.

git reset

Hard
The hard option will reset the ref pointers and also adjust the staging index and the working directory to match the state of the specified commit — it will reset everything. So, make sure that you really want to discard everything before you do the hard reset.

Hard reset

Soft
The soft option will not touch the staging index and the working directory and it will only update the ref pointers for you.

11. stash
You have been working for a while on your feature branch, but some new urgent bug popped up and you need to fix it. You were in the middle of the implementation and you don’t want to commit your changes. What you can do in this situation is to use the git stash command.
Git stash will store your changes in the stash stack and you can list them with git stash list:

Stashing changes

There are no restrictions for the branch that the stash can be applied on. You can stash changes to one branch and then apply them to a completely new one. To apply stored change you can use the git stash apply which will apply the latest changes stored in the stack. If you want to apply some older changes than you can specify the name e.g git stash apply stash@{1} to apply the second stash in the stack.
Note that after you apply the stash using the apply command the stash will not be removed from the stack.
You can use git stash pop to apply the stash and immediately remove it from the stack.
You can also use git stash drop to just remove the stash from the stack without applying it somewhere.

Applying and dropping stash

12. cherry-pick
So, what is cherry picking? It is just like Percy picking the cherries from its plate.

Percy cherry picking

Sometimes it can happen that you don’t want to merge your whole feature in the master branch and you want to pick only some of the changes. In those situations, the cherry-pick command might be handy.
After you checkout to the branch that you want to apply the changes, you can run: git cherry-pick <commit_id>
If you want to cherry pick more than one commit than you can do it by specifying their commit ids separated by space:
git cherry-pick <commid_id> <another_commit_id>
During the cherry-picking conflict can also happen. After you resolve the conflict you can continue with:
git cherry-pick --continue , and you can also abort the commit with:
git cherry-pick --abort.
Note that cherry-pick will create new commit (with new id) and you will not be able to track the history of the old commit.

13. revert
You have just pushed your work to its origin branch and realized that one of the commits should not be on that branch. You can fix that by adding another commit that will undo the commit which was a mistake. You can easily do it by using the revert command.
It takes the commit id as a parameter:git revert <commit_id>

git revert

Collaborating

14. fetch
With fetch, you download new data from a remote repository which are not applied automatically after you get them. Running git fetch will fetch branches and/or tags (collectively, “refs”) from the remote repositories along with their objects.
If no remote repository is specified, the “origin” will be used.

15. pull
With git pull, new data are downloaded from a remote repository and applied to the local repository. Running git pull will update the local branches with the changes from the remote repository.
The default way to integrate the new changes is by using a merge and it can be changed to rebase if the rebase option is used:
git pull --rebase
It is recommended to pull changes in a clean repository. That means there are no uncommitted changes in the local repository.

16. push
Now, after you committed your changes you probably want to push them to the remote repository so that they are available for your teammates.
Runninggit push will push the new changes of the current branch to its remote.
In case you created the branch locally, the whole branch should be pushed to the remote repository and you can use the following command:
git push -u origin <replace_with_branch_name> — it will push the branch with the specified name to the origin repository. The remote branch will have the same name as the local one.

17. branch
With git branch Git will print the list of your local branches. If you are interested in seeing the remote branches then git branch -r will do it for you. If you want to see both local and remote then you can use
git branch -a .
You can delete a branch with: git branch -d <branch_name>

18. remote
The remote command helps you to manage remote repositories. When collaborating you should know how to add a remote repository or how to remove one.
git remote -v — will list you the URLs that Git saved for remote repositories and their short names. When you clone a project, Git automatically adds the origin as a remote in your list.

git remote

To add a new remote repository in your list you can use:
git remote add <shortname> <url>
And to delete you can use:
git remote rm <shortname>
You can also view some information for the remote repositories:
git remote show <shortname>

19. merge
At some point, you will want to integrate your bugfix or feature branch into another branch. One of the ways to do it is by merging your branch.
For that purpose, you run the git merge command.
After you run the command, two types of merge can occur: fast-forward merge or three-way merge.

Fast forward merge occurs when there is a linear path between the branches you want to merge. For example, you created a bugfix branch from the master, you fixed the bug and now you want to merge it into the master. In meantime, no one has updated the branch and Git knows how to merge the branch itself.

Three-way merge occurs when there is no linear path between the branches. Just like the previous example, you created a bugfix branch from the master branch, you fixed the bug and now you want to merge it. But, now the difference is that in meantime, someone updated the master. So, in order to merge the branches, Git has to create a new commit in which the changes are combined. At this moment, a conflict can occur. Conflicts occur when both of the branches changed a same block of code and Git needs your help to put the changes together. At this moment you can accept one of the changes or you can combine the changes. When this happens Git modifies the affected files with visual indicators so you can easily find the conflicted area. It uses 3 visual markers:
<<<<<< — to denote where the conflict starts from
====== — to separate the changes from the branches
>>>>>> — to denote where the conflicts end

After you resolve the conflicts (and also remove the markers) the conflicted files should be added to the staging area with git add.
In case you did some mistake or you have changed your mind you can always run git merge --abort and the branch will remain unmodified.
If not, then with git commit you conclude the merge and create a new merge commit.

20. rebase
The second way to integrate changes is by using rebase first and then merge. The first thing that you need to know about rebase is that it will rewrite the history. An important thing that you should remember is that public commits should not be rebased because someone can base their work on them.

Instead of merging a specific branch into your branch you can also rebase your branch onto a specific one. So, what is actually doing this rebase command for you?
It will integrate changes of a specific branch into another branch by changing the base of the second branch from one commit to another one. At the end, it will look like the second branch was created from the first one.
In this way, your history will be linear and more clear.
You can use it like this: git rebase <name_of_branch_to_rebase_on>

This is the first mode of the rebase command — the standard one. The second mode is the interactive mode. With this mode, you can easily modify a sequence of commits before you include them in another branch (e.g its remote one).
I find it very useful to summarize a feature in one commit. During the development of a feature it often happens to me that I want to save my work, but later add something else or refactor some parts. That can end up in 3 or 4 commits for a feature where the messages of the commits are not that intuitive. So what I want to do is to squash my commits in one and modify the commit message. Let’s imagine that I want to rebase the last 3 commits. I do it like this:

git rebase

Then replace all “pick” keywords with “squash” except the first commit.

git rebase with squash option

After the changes are saved, a new screen for the commit messages will appear and there you can change the existing ones or write a completely new one message.

Exploring the past

21. log
git log will print the commit history. There are plenty of options that can be used here. Some of them are:
git log --stat — for each commit in the history, it will print a list with the names of the files which were added/modified/removed, number of added/removed lines and a summary at the end.

git log output

git log --graph — it will print ASCII graph where you can visually see the merge history.

22. diff
This command is used to output differences. It takes data sources as inputs and outputs the differences. Data sources can be files, commits, branches etc.
If you just run git diff it will print out the differences between the working directory and the latest commit - means the changes since the last commit.
To compare two commits add the hash IDs of the commits like:
git diff <hash_of_first_commit> <hash_of_second_commit>
To compare two branches you use the names of the branches like:
git diff <name_of_first_branch> <name_of_second_branch>
You can also compare specific file across branches and you can pass it as a third argument in the git diff command like:
git diff <name_of_first_branch> <name_of_second_branch> <path_of_file>

23. blame
With blame, Git will output author metadata related to specific committed lines in a given file. So, blame only works with one file and the basic command takes the path of the file as an argument:
git blame <path_to_file>
There are a lot of options that can be used like:
-e to show the user’s email address instead of the username
-w to ignore white spaces changes
-L to specify a range of line number like:
git blame -L 1 20 <file_path> to restrict the output to line 1 to 20 of the given file.

24. reflog
With reference logs or “reflogs” Git is keeping a track to updates to the tip of the branches. That means that you can view the full history of a branch (even the lost commits) up to some defined time. The basic command is :
git reflog (which is an alias of git reflog show HEAD)
It will output a list of log items for the current branch. Here is an example:

git reflog

The latest commits appear at the top and for each of items there is a syntax to access it — hash followed by name@{qualifier} and message. Many Git commands accept refs as parameters, like reset and merge.

So, how can you use this reflog? One use case can be that you want to recover a lost commit. That can happen for example, if you did some rebasing, dropped some commits and after that, you have changed your mind. Now you want to operate on some of the commits that you dropped during the rebase. Once you find the lost commit in the reflog you can pass it to a command that accepts reflogs as parameters and get it back.

25. show
Show is a nice command that is used to show information for different objects e.g commits or tags. It can be also used to show an older version of a file. For example, to show the version of a file 2 commits ago you can use the following command:
git show HEAD~2:<replace_with_file_path>

Thanks for reading!

--

--