A Practical Git Cheat Sheet

For a comprehensive cheat sheet see github's one

In rough order of importance:

Clone a repository

git clone https://special-url-you-paste-from-git-website.com/repo.git

Add a file because you want to commit it

git add filename

Add all files because you want to commit them

git add .

See the status git thinks your files are currently in

git status

Commit your changes

git commit -m "Commit message goes here"

Push your changes to the remote

git push origin branch-name

Create a new branch

git checkout -b new-branch-name

Switch to another existing branch

git checkout existing-branch-name

Get the latest version of a particular branch from github (if other people committed stuff and pushed it)

git pull origin branch-name - Warning pull also merges it the branch you're currently on. If you don't want to merge it, use git fetch.

Screwed up your repo? - start over

The Nuclear bail out ☢️

git clone the whole thing again into a new folder and start from there :smile:

See what changes you made to a file

git diff

See what changes you made to a file (but you already 'added' it)

git diff --cached

Start a new repo from existing code

cd <directory code is in>
git init

You can then git remote add origin https://special-url-you-paste-from-git-website.com/repo.git to add the website as a remote.

And then git push origin master to push it.

Move a file / folder

git mv file1 file2

Moving is a special operation in git. As well as add and remove.

You can either do a mv file1 file2. But git will think you deleted file1 and created file2. So git status will show two changes.

git mv keeps the commit history neater.

Slightly more Advanced git commands ⚠️

Use these with caution.

Uncommit your last commit ⚠️

git reset --soft HEAD~1

This leaves the changes already added but not yet committed.

To uncommit the past 3 commits is: git reset --soft HEAD~3

Delete a commit ⚠️

git reset --hard HEAD~1

Force reset a branch to something ⚠️

git reset --hard origin/master <- Goes to github of origin remote, finds master. And completely replaces the current branch you are in with those commits.