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
- Change your directory to the common SSH folder, so that the generated keys will be stored there:
cd ~/.ssh
- Run
ssh-keygen -t rsa -b 4096 -C "whatever@email.com"
, replacing the placeholder with a proper email address. - When prompted with
Enter file in which to save the key...
, enter a recognizable name for your key. I tend to use a format likejn_github
orjn_azuredevops
. -
When prompted for a passphrase, open your favorite password manager, generate a great password and store it there.
- If it doesn’t already exist, create a
config
file in the.ssh
directory. - 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>
- 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. - Done!
… Windows 10
- Install Sourcetree
- Follow the included guide to set up SSH with PuTTY (also included with the installer).
- 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:
- Ensure that you are on the
master
branch git reset HEAD~1 --soft
- things are now uncommitted from the master branch and can be committed to whatever other branch you originally intended.- 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:
- Run
git rm -r --cached .
to recursively remove all files from the index, but leaving the physical files alone. - Run
git add .
to re-add all files, excluding the ignored ones. - Commit the files:
git commit -am "Remove ignored files"
- Done!
(Thanks to StackOverflow)