Skip to main content
GitHub

Git Cheat Sheet

Prerna Sharma

What is Git?

Git is a version control system. Version control, also known as source control, is the practice of tracking and managing changes to software code. Version control systems are software tools that help software teams manage changes to source code over time.

Version control software keeps track of every modification to the code in a special database. If a mistake is made, developers can turn back the clock and compare earlier versions of the code to help fix it while minimizing disruption to all team members.

Installing Git

MacOS - Install Git with Homebrew

If you have installed Homebrew to manage packages on OS X, you can follow these instructions to install Git:

1. Open your terminal and install Git using Homebrew:

brew install git

2. Verify the installation was successful by typing which git --version:

git --version

You should be able to see the Git version.

Windows - Install Git with Chocolatey

Please follow this guide to install Git using Chocolatey, a Windows powerful package manager.

Chocolatey - A Powerful Package Manager for Windows
What is Chocolatey? Chocolatey or Choco as it is sometimes referred to, is a free, open-source package manager for windows servers that is very similar to Apt or DNF in the Linux realm. In other words, this is a program used for installing software via the Windows command line. It

Windows - Installing using Git Installer

1. Download the latest Git for Windows installer.

2. When you've successfully started the installer, you should see the Git Setup wizard screen. Follow the Next and Finish prompts to complete the installation. The default options are pretty sensible for most users.

Linux - Install with apt-get

Debian / Ubuntu (apt-get)

1. From your shell, install Git using apt-get:

sudo apt-get update
sudo apt-get install git

2. Verify the installation was successful by typing git --version:

git --version

You should be able to see the Git version.

Fedora (dnf/yum)

1. From your shell, install Git using dnf (or yum, on older versions of Fedora):

sudo dnf install git

or

sudo yum install git

2. Verify the installation was successful by typing git --version:

git --version

You should be able to see the Git version.

Configuring Git

Configure your Git username and email using the following commands, replacing Alice's name with your own. These details will be associated with any commits that you create.

git config --global user.name "Alice"
git config --global user.email "[email protected]"

Adding SSH Key

SSH (secure shell) is used for remote file transfer, network management, and remote operating system access.

Open Terminal on Mac and Linux and Git Bash on Windows

Generate an SSH Key

  1. Execute the following to begin the key creation. This command will create a new SSH key using the email as a label.
ssh-keygen -t ed25519 -C "[email protected]"

If you are using a legacy system that doesn't support the Ed25519 algorithm, use:

ssh-keygen -t rsa -b 4096 -C "[email protected]"

2. You will then be prompted to "Enter a file in which to save the key." Just Hit Enter if you don't want to specify name.

> Enter a file in which to save the key (/Users/you/.ssh/id_ALGORITHM): [Press enter]

3. The next prompt will ask for a secure passphrase. A passphrase will add an additional layer of security to the SSH and will be required anytime the SSH key is used. If someone gains access to the computer that private keys are stored on, they could also gain access to any system that uses that key. Adding a passphrase to keys will prevent this scenario. You can hit Enter if you don't want to add password.

> Enter passphrase (empty for no passphrase): [Type a passphrase or hit enter]
> Enter same passphrase again: [Type passphrase again or hit enter]

At this point, a new SSH key will have been generated at the previously specified file path i.e. /Users/you/.ssh/id_rsa

Add SSH Key to SSH Agent

eval "$(ssh-agent -s)"

Once the ssh-agent is running the following command will add the new SSH key to the local SSH agent.

ssh-add -K /Users/you/.ssh/id_rsa

Add the SSH Public Key to Your GitHub Account

You can access and write data in repositories on GitHub using SSH. When you connect via SSH, you authenticate using a private key file on your local machine with your GitHub Account which will have public key. So, let's add public key to your GitHub Account.

  1. Copy the SSH public key to your clipboard. The below command copies the contents of the id_ed25519.pub file to your clipboard. Replace you file name accordingly if you kept it different while generating the key.
pbcopy < ~/.ssh/id_ed25519.pub
💡
If pbcopy isn't working, you can locate the hidden .ssh folder, open the file in your favourite text editor, and copy it to your clipboard.
  1. Login to your GitHub Account on your favourite browser.
  2. In the upper-right corner of any page on GitHub, click your profile photo, then click  Settings.
  3. In the "Access" section of the sidebar, click  SSH and GPG keys.
  4. Click New SSH key or Add SSH key.
  5. In the "Title" field, add a descriptive label for the new key. For example, "my-key".
  6. Paste the key that you copied. It should look like:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCpgnc7BU2/ZlAYYp9lzyvoV0Ue16XR8JM2m6r9+pJz8zMvMNa49uSIRtwfe83d73kaFnqzT1oThYUDwpN1VozVBWAIVO1tn5C1RgWnmW1QqgUE8Tqczt94kiLhVnN3V2IS4c/RAyXB4FlfaMbspNFLwT2FYsn+AQ== [email protected]

Now, you should be able to communicate to your remote GitHub account from your local machine.

Git Commands

Git Basics

Command Description
git init Create empty Git repo in specified directory. Run with no arguments to initialize the current directory as a git repository.
git clone Clone repo located at onto the local machine. Original repo can be located on the local filesystem or on a remote machine via HTTP or SSH.
git config user.name Define author name to be used for all commits in the current repo. Devs commonly use --global flag to set config options for the current user.
git add Stage all changes in for the next commit. Replace with a to change a specific file.
git commit -m "" Commit the staged snapshot, but instead of launching a text editor, use as the commit message.
git status List which files are staged, unstaged, and untracked.
git log Display the entire commit history using the default format. For customization see additional options.
git diff Show unstaged changes between your index and working directory.

Undoing Changes

Command Description
git revert Create a new commit that undoes all the changes made in , then apply it to the current branch.
git reset Remove from the staging area, but leave the working directory unchanged. This unstages a file without overwriting any changes.
git clean -n Shows which files would be removed from the working directory. Use the -f flag in place of the -n flag to execute the clean.

Rewriting Git History

Command Description
git commit --amend Replace the last commit with the staged changes and last commit combined. Use with nothing staged to edit the last commit’s message.
git rebase Rebase the current branch onto . can be a commit ID, branch name, a tag, or a relative reference to HEAD.
git reflog Show a log of changes to the local repository’s HEAD. Add --relative-date flag to show date info or --all to show all refs.

Git Branches

Command Description
git branch List all of the branches in your repo. Add a argument to create a new branch with the name .
git checkout -b Create and check out a new branch named . Drop the -b flag to checkout an existing branch.
git merge Merge into the current branch.

Remote Repositories

Command Description
git remote add Create a new connection to a remote repo. After adding a remote, you can use as a shortcut for in other commands.
git fetch Fetches a specific from the repo. Leave off to fetch all remote refs.
git pull Fetch the specified remote’s copy of the current branch and immediately merge it into the local copy.
git push Push the branch to , along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist.

Git Config

Command Description
git config --global user.name Define the author name to be used for all commits by the current user.
git config --global user.email Define the author email to be used for all commits by the current user.
git config --global alias. Create a shortcut for a Git command. E.g. alias.glog "log --graph --oneline" will set git glog equivalent to git log --graph --oneline.
git config --system core.editor Set text editor used by commands for all users on the machine. arg should be the command that launches the desired editor (e.g., vi).
git config --global --edit Open the global configuration file in a text editor for manual editing.

Git Log

Command Description
git log -- Limit the number of commits by . E.g. git log -5 will limit to 5 commits.
git log --oneline Condense each commit to a single line.
git log -p Display the full diff of each commit.
git log --stat Include which files were altered and the relative number of lines that were added or deleted from each of them.
git log --author="" Search for commits by a particular author.
git log --grep="" Search for commits with a commit message that matches .
git log .. Show commits that occur between and . Args can be a commit ID, branch name, HEAD, or any other kind of revision reference.
git log -- Only display commits that have the specified file.
git log --graph --decorate --graph flag draws a text-based graph of commits on the left side of commit messages. --decorate adds names of branches or tags of commits shown.

Git Diff

Command Description
git diff HEAD Show the difference between the working directory and the last commit.
git diff --cached Show the difference between staged changes and the last commit.

Git Reset

Command Description
git reset Reset the staging area to match the most recent commit, but leave the working directory unchanged.
git reset --hard Reset the staging area and working directory to match the most recent commit and overwrites all changes in the working directory.
git reset Move the current branch tip backward to , reset the staging area to match, but leave the working directory alone.
git reset --hard Same as previous, but resets both the staging area and working directory to match. Deletes uncommitted changes, and all commits after .

Git Rebase

Command Description
git rebase -i Interactively rebase the current branch onto . Launches editor to enter commands for how each commit will be transferred to the new base.

Git Pull

Command Description
git pull --rebase Fetch the remote’s copy of the current branch and rebase it into the local copy. Uses git rebase instead of merge to integrate the branches.

Git Push

Command Description
git push --force Forces the git push even if it results in a non-fast-forward merge. Do not use the --force flag unless you’re absolutely sure you know what you’re doing.
git push --all Push all of your local branches to the specified remote.
git push --tags Tags aren’t automatically pushed when you push a branch or use the --all flag. The --tags flag sends all of your local tags to the remote repo.

I hope you liked it. Follow me on LinkedIn.