Git cheat sheet

This cheat sheet contains my go-to answers for Git-related stuff that I want to do in a consistent manner.

Setting up SSH on…

Personally, I use a single SSH key pair per Git-provider.

… macOS

  1. Change your directory to the common SSH folder, so that the generated keys will be stored there: cd ~/.ssh
  2. Run ssh-keygen -t rsa -b 4096 -C "whatever@email.com", replacing the placeholder with a proper email address.
  3. When prompted with Enter file in which to save the key..., enter a recognizable name for your key. I tend to use a format like jn_github or jn_azuredevops.
  4. When prompted for a passphrase, open your favorite password manager, generate a great password and store it there.

  5. If it doesn’t already exist, create a config file in the .ssh directory.
  6. Add the following to the config file - replace the values (currently valid for GitHub) with the correct values:
Host github.com
  HostName github.com
  User git
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/<whatever-name-you-gave-your-key>
  1. Run ssh-add -K ~/.ssh/<whatever-name-you-gave-your-key> to add your key to the SSH agent AND store the passphrase in OSX’s key chain, so you won’t ever be prompted for it again.
  2. Done!

… Windows 10

  1. Install Sourcetree
  2. Follow the included guide to set up SSH with PuTTY (also included with the installer).
  3. Done!

Fixing mistakes

For everything not mentioned here, ohshitgit.com is brilliant.

Fixing an accidental commit to master

Example: Things went a bit fast and you have now made committed something the master branch, that you meant to commit to a feature branch instead. Also, you can’t just naughty-push it to the master branch, as it is protected.

Solution for the case where you have not pushed but just committed your changes:

  1. Ensure that you are on the master branch
  2. git reset HEAD~1 --soft - things are now uncommitted from the master branch and can be committed to whatever other branch you originally intended.
  3. Done!

(Thanks to StackOverflow)

Removing ignored files from a repository

Let’s say that you have worked for some time on a repository and at some point realize that some files and folders should never have been committed. You add the things to the .gitignore file and then everything should be alright - right? No, changes are still tracked in the files that are now ignored, but already have been committed.

We can fix this by doing the following:

  1. Run git rm -r --cached . to recursively remove all files from the index, but leaving the physical files alone.
  2. Run git add . to re-add all files, excluding the ignored ones.
  3. Commit the files: git commit -am "Remove ignored files"
  4. Done!

(Thanks to StackOverflow)