Must Know Git Commands and their Uses: Complete Git Cheatsheet

Ajay Choudhury 04 Aug, 2021 12 mins
Must Know Git Commands and their Uses: Complete Git Cheatsheet

In this guide, we have compiled all the important and most used Git commands together with their usage. Follow till last to get yourself comfortable with Git and version control. Trust me if you get acquainted with Git once you won’t be able to resist using it. It is such a beautiful thing.

Often people confuse Git with GitHub and it is understandable due to the huge popularity of GitHub. GitHub is a cloud hosting service that lets you manage your Git repositories and collaborate with other people using Git. While Git is an open-source distributed version control system that helps track changes and versions of your work.

How Git Works?

Git is an open-source distributed version control system, which means you can too contribute to the code of Git and make it better. It works by distributing work to many levels and people and saves only changes each time with author and date. Anyone can pull a copy of your project and keep it, they can add changes to it as well and can request you to merge them into the original version of the project i.e. your copy.

We should learn Git commands along with other GUIs as it gives better command over the system because with commands we understand each action and what it is doing. Also using CLI is faster than using GUIs.

Installation of Git

In Windows 10

Git has both CLI and GUIs available but we will learn Git CLI in this guide, Git GUIs are self-explanatory, though you can follow the guide for GitHub Desktop here. You can download the Git CLI from its official site for Windows, macOS or Linux. On Windows the installation process is very simple, like any other software, you just need to press the “Next” button a few times and the Git CLI will be ready to work. You need not do anything on the installation screen as default settings are perfect for most people.

On macOS

If you have installed XCode or its Command Line Tools on your Mac then Git may be already installed on your device. You can check the version of Git using the command

git --version

If you do not have Git installed, you need not worry at all. You can download the Git for Mac installer and follow the prompts to install Git on your Mac. Or, if you have installed Homebrew to manage packages on OS X, you can follow the command below to install Git on your Mac.

$ brew install git

You can verify the installation by checking the version of Git using the command given above.

On Linux

The process of installing Git on Linux is very similar to that of macOS. You just need to type sudo apt-get install git on the terminal and Git will be installed. You can verify the installation by checking the version of Git installed.

sudo apt-get update
sudo apt-get install git
git --version

We have prepared this tutorial on a Windows device, but the commands and their usage remains the same in all the environments and it works with the same efficiency. You can seamlessly follow the guide irrespective of your operating system and its version.

What is Git Bash?

Git Bash is basically an application that provides a Unix based shell to emulate the Git CLI on Windows environment. Bash is the acronym for Bourne Again Shell and a shell is a terminal application that lets users connect to the operating system through the command-line interface. Git Bash is a package that installs Bash, some Bash utilities and Git on Windows environment. It helps us connect to and control some Git elements and our project repositories using commands.

Git Bash as mentioned above is a Unix based shell and it lets users use Git on it that does not mean it is meant for Git only, you can use Git Bash as a full-fledged terminal that is quite similar to the terminal in Linux.

Basic Git Commands and their Uses

We will now explore how to use various Git commands and will understand the operations performed by Git. To understand this better we will create a separate folder somewhere and inside the same folder, we will right-click and run Git Bash inside which we will be running and testing our Git commands. Also, create 2-3 dummy HTML files for understanding the concepts more practically.

git config

git config --global user.name Ajay

Configures the user globally for the system and every commit in that system is by default registered to that user.

git config --global user.email ajay@example.com

The above command similarly configures your email-id globally for commits on and from your device until you explicitly change it for a project.

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

It returns the name of the global user, similarly, you can view the email id of the user using the second command.

git config user.name Alex
git config user.name alex@orbitgadget.com

The two commands above can be used to set repository-specific username/email configuration. For this, you need to move to the working directory in Git Bash or directly open the Git Bash inside the working directory.

git init

git init

The above command initializes a new Git repository from scratch and creates a hidden folder within the directory that tracks the work of the repository for version control. You can also clone an existing repository using the command git clone repo_url. You can see the hidden .git folder using the command ls -lart on the terminal.

git status

git status

It shows the status of the files in the directory whether they are untracked, staged, unmodified, modified or committed. You can better understand the states of a file with the illustration given below.

git status -s

It is similar to git status but it shows the status using symbols. An example of the output of git status -s in different scenarios is given below.

Status of files in git

Staging

git add your_file.extension

It adds the file to the staging area and hence takes a snapshot of the changes performed in the file and includes it in the project’s history.

git add -A 

It adds all the untracked files to the staging area. Then if you change the files, git status returns the modified tag beside the file. You can again add the modified files to the staging area using the git add -A or git add . command.

Commit

git commit

Commits the staged files finally. After git commit you will be asked to enter a commit message, press i to start insert mode and then type your message and press :wq to save and exit.

git commit -m "initial commit"

Use this command to directly commit the files with a given commit message. My message is initial commit, replace it with your own.

git commit -a -m "your_commit_message"

Skips staging and directly commits all the files. It is not recommended most of the time as staging has its own benefits..

Checkout

git checkout index.html

It matches your file (here, index.html) to the last commit and restores the earlier version. It is useful if something went wrong in a particular file and you want to restore the earlier version of it.

git checkout -f

It matches the whole directory to the last commit and restores the earlier version of all the items in the directory.

Log

git log

It shows who committed what and at what time along with the commit messages. You can exit out of the log by pressing “q” from the keyboard.

git log -p -5

Shows the same details of the last 5 commits. Similarly, if you want to view the details for the last two commits, you can use git log -p -2.

Difference

git diff

Compares working untracked files with the staged files and highlights the changes. If we add all the modified files to the staging area then it returns nothing as there is nothing to compare.

git diff --staged

Compares staging area with the last commit and highlights all the changes.

Cached Files

git rm index.html

The above command deletes the file (here index.html) from the staging area as well as from the working directory.

git rm --cached index.html

Removes the file only from the staging area.

git rm -r --cached .

The above command removes everything from git's tracking and you will have to commit once again to take all files into consideration. It is useful when .gitignore fails to detect mentioned files.

What is .gitignore?

Git is an advanced version control system and an advanced system, it cannot follow a space-consuming architecture. So being smart, it tracks only source codes and ignores the automatically generated files like logs, output files of the source code and other automatically generated files. At the same time, to prevent any mishap it gives full control of ignoring such files to the master. Hence, we can create a .gitignore file and list all the unnecessary files which are not important and can slow down your push/pull speed.

touch .gitignore

It is a bash command used to create .gitignore file in the working directory. You can now open .gitignore in any advanced text editor like VSCode and list down all the files which need not be tracked by Git.

errors.log

It will ignore the file errors.log from all the directories and subdirectories of the working directory.

*.html

Will ensure that any HTML files in all directories and subdirectories get ignored. It could be any extension (I used .html for reference it could be any extension like .log.png, etc.).

/index.html

Only ignores the HTML file in the root directory where .gitignore is present.

__pycache__/

Ignores the complete subdirectory or folder named __pycache__. You can ignore any folder you want using this pattern in .gitignore.

Branches

Branches are basically separate copies of the main/master branch that are meant for development or modification purposes. For example, if a project is in production and you want to modify it or develop some new feature in it then, it is obvious that you won’t like to try changing the project on production directly, you will try and test your changes before pushing it into the production. The same feature is provided by Git with the help of branches.

git branch tester

Creates a branch with the name tester which is an exact replica of the master branch but any operation performed in this branch won’t be reflected in the master branch. You will have to manually switch to the new branch if you want to work in the new branch.

git branch

Gives a list of all the existing branches of the current project. It gives a star beside your current branch to specify which branch you are currently in.

git checkout branch_name

Changes your current branch to branch_name without affecting your work in the current branch.

git branch -m oldname newname

Changes the name of the branch from oldname to newname.

git branch -m newname

Changes the name of the current branch to newname.

git merge tester

The above command merges the work of the branch tester to the master branch. Run this command being on master branch. The command git log -p -5 will now show the last 5 commits including the commits of the branch tester.

git checkout -b tester

Creates a branch named tester and switches to that branch automatically. You need not switch to the new branch manually if you use this command.

Remote Repository on GitHub

We can create a remote repository on GitHub or any other Git hosting services like BitbucketGitLab, etc. The process of creating an account on GitHub is fairly simple and user-friendly.

After creating your GitHub account, there are two ways of authenticating the account on Git, a sign-in pop up while you add a remote repository to the Git project or using an SSH key. Using an SSH key is more secure and satisfying and it is a must for private repositories. You can follow this guide to generate and link the SSH key to your account. You can also find the link to the guide on your GitHub account’s ‘Settings’ under the ‘SSH and GPG keys’ tab.

Authenticate your device with SSH

Now, you can create your first repository on GitHub by clicking on the ‘New’ button and fill in all the details for the new repository. You can add a Readme file too which will contain all information about your repository. You can use tools like readme.so to create an intuitive readme file very quickly.

Create new repository

You can get the URL and SSH to any public repository by clicking on the ‘Code’ button as shown in the image below.

Get the URL of the public remote repository

git remote add origin your_github_repo_url/ssh

Links your remote repository to the current project and gives the name origin to the particular remote repository.

git remote

Shows all the names of the remote repositories linked with the current project.

git remote -v

Shows all the linked remote repositories along with their URLs.

git push origin master

Pushes your local master branch to the master branch of the remote repository added with the name origin.

git push -u origin master

Pushes the branch master to the remote repository and sets it to default such that any further pushes using git push or git push origin master is a push from the local master branch.

git push origin tester

Pushes the branch tester to the remote repository.

git push origin --all

Pushes all the branches from the local repository to the remote repository named origin.

git push -f origin master

Forcefully pushes the local master branch to the remote master branch.

git push origin master:main

Pushes the local master branch to the remote main branch. It is particularly useful for GitHub as on GitHub the default repository is changed from master to main.

git fetch origin

Downloads all history from remote-tracking branches.

git remote set-url origin new_url/ssh

Changes the URL of the remote repository named as origin from its old URL to the new_url/ssh.

git pull main:master

Downloads and updates all the content from the remote repository to the local repository. It ensures that the local repository is on the same level as the remote repository.

git clone repo_url

Clones an existing repository (whose URL is provided) to the current folder with the repository’s name.

git clone repo_url folder_name

Clones an existing repository with the name folder_name.

git clone repo_url .

Clones the content of the remote repository inside the current folder without wrapping them in any folder.

Change Default Repository in GitHub

There has been a recent update in GitHub, according to which the default repository in GitHub has been named as main, earlier it was master. So, if you push your local master branch to the remote repository on GitHub, it will create a new branch master. You can change the default branch of that repository by heading to ‘Repository Settings’ >> ‘Branches Tab’ >> ‘Switch to another branch’. See the image below for reference.

Switch default repository in GitHub

You can also change your default branch settings for all your repositories by going to ‘Account Settings’ >> ‘Repositories Tab’ >> ‘Update default branch name’. See the image below for reference.

Change default branch for all repositories

Conclusion

This guide is a very good platform for beginner’s to get introduced to Git and start using it in their projects. The commands provided above are some of the most used Git commands and most of the time, beginners won’t be requiring other Git commands but if you need to perform some other action, you can always try putting your queries on Google and explore the solutions. We have tried to give you a start with Git, there are much more things you can do with Git and GitHub. The more you explore, the more you will learn.

We hope you liked this article, there are many more such guides on our blog. You can try reading the list of Linux commands and 100 Windows 10 shortcuts that can make your life easy.

Kindly share this article with your friends or colleagues who are looking towards starting off with Git and GitHub. You can comment down your queries or feedback in the comment section below.

Was this Article Helpful?

Ajay Choudhury

Ajay Choudhury

A learner and a student of technlogy. He loves sharing experiences and learning with others through his projects and blog. Along with technology, he loves playing football and enjoys listening to music and podcasts.

0 Comments

Info

Contribute to make this site more awesome →