How to get Started with git - a beginner cheat sheet

Feb 6, 2020 | 10 min read

Now it’s time to get your feet wet, if you are new to git, then read the blog: Vocabulary of git - a beginner guide , before reading this article. Also, if you already are familiar with the basic functions of git and looking for advanced learning then , visit blog : Advanced git concepts - All you need to learn to be a pro git user.

First of all , if you don't have git installed in your computer, based on the type of operating system you are on , you can download and install git in your computer.

Okay, then if you have installed git on your pc. Now it's time to check if git is successfully installed. You can check the version of git installed , using the following command:

$ git --version

git version 2.25.0

If you got the version of git then, we are good to go , git has been installed and now you can follow this cheatsheet.

Now let's dig into it:

If this is the first time you are using git in your system, then it's needed to configure your git, but you can change them later anytime , if you like to:

You can use git config to configure your git environment , like defining user name, email and so on :

To view all the configurations that can be updated in your git are:

$ git config --list 

user.name=Sagar
user.email=sagar.chapagain@*********
pull.rebase=true
init.defaultbranch=main
core.editor=code --wait
core.excludesfile=/Users/urzadevkota/.gitignore_global
core.ignorecase=false
difftool.sourcetree.cmd=opendiff "$LOCAL" "$REMOTE"
difftool.sourcetree.path=
mergetool.sourcetree.cmd=/Applications/Sourcetree 2.app/Contents/Resources/opendiff-w.sh "$LOCAL" "$REMOTE" -ancestor "$BASE" -merge "$MERGED"
mergetool.sourcetree.trustexitcode=true
commit.template=/Users/urzadevkota/.stCommitMsg
safe.directory=/Volumes/Files & Storage/codes/js/jobaxle

But it is not necessary to fully understand, but let me walk you through some :

$ git config --global user.name "John Doe" #sets the user name to John doe
$ git config --global user.email "john@doe.com" # sets the email
$ git config --global pull.rebase false # sets the setting of rebase
$ git config --global init.defaultbranch "main" #sets the default branch to main or as per your choice 
$ git config --global core.editor=code --wait #sets the default text editor ,for windows : add path of texteditor app

Note: the text after # is comment for you to understand and should not be used as a command

Note : - -global option is used to set the global configuration i.e. same for all the projects.

If you want to set these config specific to each project then you can do this by running git config commands without the --global option for your specific project.

You can also check each variable independently by :

$ git config user.name
$ git config user.email 

and so on for all variables.

With these settings done, your configuration is now completed. Now you are ready to learn . The basic assumption beyond this point is that, you have basic knowledge on various git stages and fundamentals of how git works , If you are new to what I just said before continuing this chapter, it is advisable to go through this blog: Vocabulary of git - a beginner guide .

Now to get started , you typically require a Git repository, which can be obtained in one of two ways:

  1. Either you can take a local directory that is currently not under version control, and turn it into a Git repository, for which you can initialize an empty project with the git init command.
  2. Or , You can clone an existing Git repository from elsewhere. In either case, you end up with a Git repository on your local machine, ready for work using git clone command.

Which one to pick up depends solely on your project need, if you are starting a fresh project from scratch ,then you would prefer to use the first method i.e. to initialize the project or else if your project is already setup and you will be continuing the project from there, which is already in git then you will need to clone it from your repository.

Basics git commands:

git help : It shows help for a specific git command

git init: Creates a new git repo for a new folder, and initializes with adding a .git folder.

git status or git status -s (for short status): This command tells you about the changes and modification for the current working directory. With -s flag the status will be compact then the usual one.

$  git status

On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
  new file: README
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  modified: CONTRIBUTING.md

To understand what git status result actually mean , there are basically two sections :

Changes to be committed: The files under this title are already added to the staging area, i.e. these can be directly committed to the git as a history to the git database with git commit command ,will be discussed below

While , ​​Changes not staged for commit: The files under this heading are not added to the staging area so when you run git commit command , these files’s snapshot will not be added to the git database .

If you need to commit files shown is not staged for commit you need to add these files , to the current commit history you need to add these files in to staging area which can be done using git add command, discussed below:

git add or (git add . ) adds files to the staging area, you can add specific files using filename or use (.) to instruct all modified and unstaged files to be added to the staging area.

git commit: creates a new commit ,and opens up a text editor to prompt you to add a commit message. Once a commit message is added, closing the editor will commit the code.

git commit -m ‘fix: Working on documentation’ : Creates a new commit with message as given, so it won’t open up a text editor

git commit -a -m ‘fix: Working on documentation’ : This command executes two commands at once, i.e. first it adds files to staging area using command <git add . > then it executes < git commit -m ‘fix: Working on documentation’> hence, if you want to add all the modified files to current commit history directly, you don’t have to run git add explicitly , if you use this command

git log: shows a log of history of commits in a reverse chronological order i.e. recent first. This shows various information of logs including SHA-1 checksum, the author’s name and email, the date written, and the commit message.

The command comes with a lot of options:

git log -p : Shows log with patch (difference in code) in each commit. This command is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added.

git log -p -n : Displays last n commit history with patch (changes)

git log --stat : Shows log of commits, including statistics of the commit like no of files changed, no of lines added or removed and so on .

git log –(since/before/after/until): One of since ,before, after , until takes various types of date format , you can specify a specific date like "2008-01-15", or a relative date such as "2 years 1 day 3 minutes ago".

$ git log --since=2.weeks

git log --all --graph --decorate: Visualizes history as a DAG

git diff < filename > :

It is a useful command, to view what has been changed in the files so far. This command compares for a file , what is in your working directory with what is in your staging area. The result tells you the changes you’ve made that you haven’t yet staged. Note that git diff by itself doesn’t show all changes made since your last

commit ,rather it only shows changes that are still unstaged. If you’ve staged all of your changes, git diff will give you no output.

git diff --cached or git diff --staged : Without any options with git diff will show only difference that is not staged, i.e. if you have a file staged then git diff will show no output but if you want to see the changes added to staged then you need to use –cached or –staged options.

*NOTE : It is always advisable to check or review the code using <git diff –>,for what has been changed in this commit, before actually committing by using this command*

git rm < filename >: If you need to remove your files that are already added in the staging area, you need to remove it from the staging area before, and then commit. The git rm command does that, and also removes the file from your working directory. You can pass files, directories, and file-glob patterns to the git rm command. That means you can do things such as:

$ git rm log/\*.log

*NOTE : If you remove the file without using this command from your working directory, it shows up under the “Changes not staged for commit” and it will remain forever.*

git rm --cached : If you don’t want a file to be removed from your drive or directory but want to remove only from git tracking then you run git rm with cached options. This is particularly useful sometimes when you forgot to add something to your .gitignore file and accidentally staged the file, then to remove it from tracking and finally adding it to .gitignore will solve the problem.

git mv : This command is used to rename a file that is already staged in git. This function first renames the file in the working directory then adds the update to the staged area.

git reset HEAD or git restore –staged :This command is used to reset or restore a file that was in the staging area , effectively "unstaging" any changes that were previously added to the staging area , So that this file will not be committed in the next commit . After running this command , If you want to commit, you need to run git add to add it to the staged area again. Git reset command was replaced by git restore, after Git version 2.23.0 onward, although it supports both for now.

Why is it necessary to move a file staged to unstaged?

A good rule of thumb for a proper commit is that , each commit is associated with meaningful commit message, and related files files associated to that commit, sometimes some unrelated files can be added when stashing, so to avoid those files to make it referenced to that commit history ,we can use git reset or restore command to unstage the file or content.

git restore : This command is used when you make changes to a file after a commit , but later you realize that you don't need this code anymore, in this case you can use this command to restore the file to discard the recent changes and restore to the version, that was in the last commit.

*Note : git restore and git restore –staged has a clear distinction in use, so you need to be clear which one to use in your need.*

  • git restore restores file by discarding the changes made after the last commit and moving it to the last committed version. i.e. it clearly does modify the content of the file.
  • while git restore –staged command does not modify the content of the file itself , but it moves changes from the staging area back into the working directory(unstage), effectively reversing the git add operation for that file

*Note : Reset and Restore can sometimes be dangerous , especially when using options of reset like –hard or git restore ,inappropriately . Once the uncommitted changes are gone after reset , or restore command then it is almost impossible to revert them back .*

git checkout : updates HEAD and current branch

Branching and merging

Branching in version control is a concept, which means that you diverge from the main line of code and continue to develop without interfering with the main line of development so you can test and verify, then only merge with the main development branch. Unlike other VCSs, Git encourages workflows that branch and merge often, even multiple times in a day. Understanding and mastering this feature gives you a powerful and unique tool and can entirely change the way that you develop.

git branch: Lists all the local branches, * indicates the current branch

git branch branch-name: Creates a new local branch in the repository

git checkout branch-name: Switch to another branch named branch-name

git checkout -b branch-name: This function, run two commands, i.e. first creates a branch using git branch branch-name and switches to it using git checkout branch-name

git merge : Merges branch named branch into current branch(main)

Working with Remotes

Remote repositories are the versions of repository that are hosted on the Internet or

network public or private. Collaborating with teams includes pushing the code from remote repositories or pulling them . Knowing how to add , view , remove repositories and work with remote branches .

*Note : It is entirely possible that you can be working with a “remote” repository that is, in fact, on the same host you are. The word “remote” does not necessarily imply that the repository is somewhere else on the network or Internet, only that it is elsewhere. Working with such a remote repository would still involve all the standard pushing, pulling and fetching operations as with any other remote.*

git clone <local_directory_name> : Download the repository entirely from the remote branch to make a local copy. In this case the remote repository is configured automatically, unlike if you have initially started working on a project from your scratch.

git clone https://github.com/schacon/ticgit  git-book

git remote: Lists the local aliases (names) of remote repositories associated with your local Git repository. These aliases are used to interact with remote repositories and perform Git operations that involve fetching, pulling, pushing, and syncing changes between local and remote repositories.

$ git remote
Origin

git remote add : Adds a new remote git repository as a short name you can reference easily.

$  git remote add origin https://github.com/paulboone/ticgit

git remote -v: View the remote repositories of the current local repositories. There can be a case that remote repositories of a project can be more than one for a local git repository.

$ git remote -v
origin https://github.com/paulboone/ticgit (fetch)
origin https://github.com/paulboone/ticgit (push)

git push : send objects to remote, and update remote reference

$ git pull origin main

git fetch: git fetch retrieves the latest changes from a remote repository without integrating them into your current working branch.

 $ git fetch https://github.com/paulboone/ticgi

git pull : git pull fetches the latest changes from the remote repository and automatically integrates (merges) them into your current local branch. I.e. two steps are involved with git pull

  • generally fetches data from the server you originally cloned from
  • Merges your current branch with remote branch
$ git pull origin main

git remote show : It lists the URL for the remote repository as well as the tracking branch information. The command helpfully tells you that if you’re on the master branch and you run git pull, it will automatically merge the remote’s master branch into the local one after it has been fetched. It also lists all the remote references it has pulled down.

git remote rename : Rename a remote url alias.

$ git remote rename paul test

Ignoring Files to track by git:

Often, there are files that you don’t want to commit to your git repository, files generated by the system i.e. log files or files that are specific to an environment i.e. env files are not generally preferred to track, and so , you can create a file with name (.gitignore) and add listing patterns to match them in the file( .gitignore).

It is always advisable , to set up a .gitignore file at the very first of starting a repository so that you don't accidentally commit the files that you don;t want git to track.

Rules for adding to .gitignore

  • Blank lines or lines starting with ( # ) are ignored.
  • Standard glob patterns work, and will be applied recursively throughout the entire working tree.
  • You can start patterns with a forward slash (/) to avoid recursivity.
  • You can end patterns with a forward slash (/) to specify a directory.
  • You can negate a pattern by starting it with an exclamation point (!).
  • You can match zero or more characters in a path segment with (*)
  • You can match on one character in a path segment with (?)
  • You can match any number of path segments using (**)
# ignore all .a files
*.a
# but do track lib.a, even though you're ignoring .a files above
!lib.a
# only ignore the TODO file in the current directory, not subdir/TODO
/TODO
# ignore all files in any directory named build
build/
# ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt
# ignore all .pdf files in the doc/ directory and any of its subdirectories
doc/**/*.pdf

*Important Notes: Remember, anything that is committed in Git can almost always be recovered. Even commits that were on branches that were deleted or commits that were overwritten with an --amend commit can be recovered. However, anything you lose that was not committed is likely never to be seen again.*

Other blog series on git:

  1. Vocabulary of git - a begineer guide to understanding git
  2. Advanced git concepts - All you need to know to be a pro git user
Author Profile Picture

Sagar Chapagain

I am a Software Engineer, a Solution Architect,a Mentor, a Trainor, a Technologist, Speaker, from land of Himalays, Enthusiasts in Tech, Investment and Economy, with a total years of experience in field of software and application development, Deployment .