[git, commands, important, essential, cheat]


Overview

This is a summary of the most important Git commands.

Code

Clone (“download”) the repository to your computer.

git clone <URL>
Warning

Do not clone a repository into another repository!


Check which files/directories have changed since your last commit.

git status

Add specified file(s) to the staging area, so that any changes can eventually be committed.

git add <file_name>

Commit staged changes to the version history of your repository. It’s good practice to use a clear & concise commit message (“note to your future self and others”) which shows up prominently on your repository at GitHub.com.

git commit -m "<your_message>"

Push any changes you have done to the repository on your computer to the specified branch of the remote repository (e.g., at GitHub.com).

git push origin <branch_name>

View your commit history (i.e., a list of commit IDs and your commit messages.

git log

Advanced use cases

Add all files to the staging area

To add all files that have been changed to the staging area (to eventually commit them), use

git add .

That way, you don’t have to mention files individually. But beware to not accidentally version files that must not be versioned (e.g., datasets).

Ignore files from versioning

You can create a .gitignore file (e.g., in the root directory of your repository) to tell Git to stop paying attention to files you don’t want to version (e.g., datasets, operation-specific files like Mac’s .DS_Store or R’s .RHistory.

For example, if you save the snippet below in a file called .gitignore, any content in the my_passwords folder and any .csv files will be ignored - even when using git add .!

my_passwords/*
*.csv

Undo previous commits

It happens to all of us - we sometimes commit stuff that we didn’t mean to commit. That can be quite problematic, for example if you’ve accidentally committed a password. But even for less drastic cases, reverting “wrong” commits is good practice because it keeps your repository clean.

The snippet below undoes the last commit.

git reset --soft HEAD~1

Alternatively, you can view the commit history with git log, and revert to any commit by referring to its unique id (which looks a bit like this: 0hf1u7x2).

git reset --hard <commit id>

See also