Git Handbook

James Clark
2 min readJun 14, 2021
Photo by Yancy Min on Unsplash

This guide to Git aims to describe the most commonly used Git commands, with a bit of an explanation of what they do.

Git commands

Initialise

Initialise a folder with Git

git init

Clone a repository (repo)

This is how you make a local copy of a repository from a hosted Git platform like GitHub/GitLab

git clone git@github.com:expressjs/express.git

View summary of local changes

To view a summary of which files have changed locally:

git status

This will show files previously known by Git that have changed as well as new “untracked” files that Git doesn’t know about.

View diff of changes

This command will show you a diff of the changes across all files or the specified ones

git diff
or
git diff file1 file2

Add files to a commit

Having made changes to some files, you need to add these changed files to a sort of staging area before making the commit.

git add file1 folder/file2 file3

Another way is like this, which will add all modified and new untracked files.

git add .

A third way is like this, which will just add the modified tracked files.

git add -u

Yet another way is to do this, which will split your changes into small “hunks” or chunks allowing you to only add parts of files. You enter “y” or “n” on each one to add it or not

git add -p

Commit

When ready to actually do the commit, you can do:

git commit -m 'Some message to describe the commit'

Push

If you are working with a remote/hosted Git platform such as GitHub/GitLab, you will need to push. This can be after one or more commits locally.

git push

Note that if this is your first push to the remote on the current branch then you may need to do:

git push -u origin main

(Note: main is starting to replace master as the default branch)

Create and switch to a new branch

git checkout -b new_branch_name

When pushing a branch for the first time you will need to do:

git push -u origin new_branch_name

Switch to an existing branch

git checkout branch_to_switch_to

Undo 1 (or more) commits

git reset HEAD~1

Replace the 1 with another number. You can use git log to see the commits and work out how many to rollback

--

--