Cheat Sheets

Git

Created: 2017 May 19th

Updated: 2019 May 9th

This is just stuff that I have put down that I find I use a lot of the time for my own reference.

Add a new repo from your machine to GitHub

1echo "# name-of-your-awesome-repo" >> README.md # add repo name to README.md
2git init # init the repository
3git add README.md
4git commit -m "first commit"
5git remote add origin https://github.com/spences10/name-of-your-awesome-repo.git
6git push -u origin master

The first four commands can be ignored if you have done more work on the repo than adding a README.md

Latest changes from repo to your machine

1git pull

Add tracking information to your work

Assuming that you are working on the master branch then

1git branch --set-upstream-to=origin/master

You can set it to whatever branch you want to track changes for

1git branch --set-upstream-to=origin/<branch>

This will mean you can just do git pull and the latest changes will be pulled to your origin

What branch

1git branch # shows what branch you're on
2git branch -r # shows remote branches
3git branch -a # shows all branches

Create a local branch and push it to GitHub

Want to make your feature branch and get it on GitHub?

Make your branch first then:

1git push --set-upstream origin <branch-you-just-created>

Create a PR [Pull Request]

Fork other users repo in GitHub, then clone to your machine.

1git clone https://github.com/YourUserName/awesome-awesome-repo

Add the remote repo:

1git remote add upstream https://github.com/OtherUserName/awesome-awesome-repo

Create your branch:

1git branch your-awesome-branch

Check it out:

1git checkout your-awesome-branch

If adding a folder use.

1git add nameOfFolder/\\*

Make your commit and push to your new branch.

1git add .
2git commit -m 'initial commit'
3git push origin your-awesome-branch

Manage the rest of the PR via GitHub

Check remotes

1git remote -v

Sync a remote fork on your machine

First configure the local to point to the remote upstream

1git remote -v
2git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
3git remote -v
4git fetch upstream
5git checkout master
6git merge upstream/master

You then use git merge to update any branch on the upstream repository:

1git merge upstream/dev

Take a look at syncing a fork for more details.

Sync a remote fork on Github

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.
  4. Click on Try switching the base. Now GitHub will compare your fork with the original, and you should see all the latest changes.
  5. Click on Click to create a pull request for this comparison and assign a predictable name to your pull request (e.g., Update from original).
  6. Click on Send pull request.
  7. Scroll down and click Merge pull request and finally Confirm merge. If your fork didn’t have any changes, you will be able to merge it automatically.

2fa

Using two factor authentication? Then use the following so you’re not adding in your auth token each time you want to push your code.

1git remote set-url origin https://yourgithubuser:your-token@github.com/yourgithubuser/yourrepo.git

Change origin url

If you want to change the origin url you can use the set-url command

1git remote set-url origin https://github.com/user/new-repo-name

Add code on your machine to new repo

Via terminal navigate to your code folder.

1git init

Add your files.

1git add .

Adding a folder use the following syntax or it’ll get added as a BLOB.

1git add nameOfFolder/\\*

Commit to local repo.

1git commit -m 'some detailed message'

To add your files to the remote repo, first add your remote repo

1git remote add origin [remote repository URL] # Sets the new remote
2git remote -v # Verifies the new remote URL
3git push origin master

For more info check out: adding an existing project to github using the command line

Delete branches

Delete local branch.

1git branch -D branch-name

Remove local branches that are not on the remote.

1git remote prune origin

Remove local branches that were created from remote branches.

1git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d

Merge master branch into feature branch

How to merge the master branch into the feature branch? This will come up often if you are workingon a team with other devs and you want to update your feature branch to include the latest changes.

1# checkout your feature branch
2git checkout feature1
3# merge master into it
4git merge master

Merge two repos

If you want to merge project-a into project-b:

1cd path/to/project-b
2git remote add project-a path/to/project-a
3git fetch project-a
4git merge --allow-unrelated-histories project-a/master # or whichever branch you want to merge
5git remote remove project-a

Stop tracking a file

If you have .env files that are tracked by Git and want to ignore them so your API keys don’t get added to GitHub use:

1git update-index --assume-unchanged <file>

Stop tracking a previously tracked folder

First add the folder to your .gitignore then remove the folder from your local git tracking with:

1git rm -r --cached <folder>

Start tracking a previously un-tracked file

1git update-index --no-assume-unchanged <file>

Cloning a repo from someone else’s GitHub and pushing it to a repo on my GitHub

So you make a clone, make some changes then realise that you need to add it to your GitHub account before making a pull

1git remote -v
2origin https://github.com/OtherUser/OtherUserRepo (fetch)
3origin https://github.com/OtherUser/OtherUserRepo (push)

You just need to set the origin to yours then add the upstream as the original origin make sense?

So change origin to yours:

1git remote set-url origin http://github.com/YourUser/YourRepo

Then add upsrtream as theirs:

1git remote add upstream https://github.com/OtherUser/OtherUserRepo

Now it should look something like this:

1git remote -v
2origin http://github.com/YourUser/YourRepo (fetch)
3origin http://github.com/YourUser/YourRepo (push)
4upstream https://github.com/OtherUser/OtherUserRepo (fetch)
5upstream https://github.com/OtherUser/OtherUserRepo (push)

Remove an upstream repository

If you no longer need a reference to a forked repository then remove it with the following:

1git remote rm upstream

Clone a repo and give it a different name

1git clone https://github.com/user/repoNameYouToChange NameYouWantToGiveToRepo

Using Husky?

If you are pushing right after a commit, you can use git push --no-verify to avoid running all the tests again.

If you make a trivial change and want to commit git commit -m 'some detailed message' --no-verify will skip your precommit and prepush scripts.

How to read last commit comment?

1git show # is the fastest to type, but shows you the diff as well.
2git log -1 # is fast and simple.
3git log -1 --pretty=%B # if you need just the commit message and nothing else.

Remove commit from pull request

Read this for more detail on how to revert.

This was the simplest approach I found:

1# Checkout the desired branch
2git checkout <branch>
3# Undo the desired commit
4git revert <commit>
5# Update the remote with the undo of the code
6git push origin <branch>

Rather than use the last part I unstaged the changes in VSCode which I think did the same thing.

Show .gitconfig details

There are there are three leves for Git config:

System level

1# to view
2git config --list --system
3# to set
4git config --system color.ui true

Global level

1# to view
2git config --list --global
3# to set
4git config --global user.name xyz

Repository level

1# to view
2git config --list --local
3# to set
4git config --local core.ignorecase true # (--local optional)
5# to edit repository config file
6git config --edit --local # (--local optional)

View All Settings

1git config --list --show-origin

info

Conflicts between Windows Git and WSL Git?

If you are having issues with changes showing in Windows Git and not Windows Subsystem Linux Git (For a Windows WSL Dev set-up) then check the settings of each environment by using:

1git config --list --show-origin

Remove any conflicting settings then try again.

If you want to rename a branch while pointed to any branch, do:

1git branch -m <oldname> <newname>

If you want to rename the current branch, you can do:

1git branch -m <newname>

A way to remember this, is -m is for “move” (or mv), which is how you rename files.

Git ref log

Want to know what work you have done on a repo? Use git reflog to displpay all the commits.

1# show all changes for the last 90 days
2git reflog show -a
3# show changes with a date
4git reflog --date=iso

https://stackoverflow.com/questions/17369254/is-there-a-way-to-cause-git-reflog-to-show-a-date-alongside-each-entry

Use SSH in place of HTTPS

Get your SSH set up on your machine and add a key to GitHub, more on that here: https://egghead.io/lessons/javascript-how-to-authenticate-with-github-using-ssh

You will then need to pick your Clone with SSH option from the Clone or download section on your repo page.

Once you have taken the link from there you will need to set the repo remote to the SSH URL

1git remote set-url origin git@github.com:username/repo-name-here.git

Where username is the username of the repo owner and repo-name-here is the name of that user’s repository.

How to authenticate with GitHub using SSH

Check that there are no rsa files here before continuing, use (bash or Git bash if you’re on Windows):

1ls -al ~/.ssh

If there’s nothing there then generate a new keygen with:

1ssh-keygen -t rsa -b 4096 -C your@email.com # add your email address 👍

If you decide to use a password for your SSH key see SSH Keys With Passwords

Now using ls -al ~/.ssh will show our id_rsa.pub file.

Add the SSH key to the SSH agent:

1# for mac and Linux from bash, also from Windows Git Bash
2eval "$(ssh-agent -s)"
3# for Git Bash on Windows
4eval `ssh-agent -s`
5# fir Fish shell
6eval (ssh-agent -c)

Add RSA key to SSH with:

1ssh-add ~/.ssh/id_rsa

Copy your key to clipboard with one of the following:

1clip < ~/.ssh/id_rsa.pub # Windows
2cat ~/.ssh/id_rsa.pub # Linux
3pbcopy < ~/.ssh/id_github.pub # Mac

Add a new SSH Key to your GitHub profile from the settings page by clicking the New SSH key button and paste in your key. Save it…

Then authenticate with:

1ssh -T git@github.com

If you go back to the GitHub setting page and refresh the key icon should go from black to green. 🎉

SSH Keys With Passwords

If you add a password to your SSH key you will find yourself entering the password to authenticate on each [pull, push] operation. This can get tedious, especially if you have a long password in your keys.

Add the following line to your ~/.ssh/config/ file:

1AddKeysToAgent yes

Open or create the ~/.ssh/config file with:

1nano ~/.ssh/config

The SSH agent will also need to be started on each terminal session now to store the keys in, add the follwowinf to your ~/.bashrc file:

1[ -z "$SSH_AUTH_SOCK" ] && eval "$(ssh-agent -s)"

Open the ~/.bashrc file with:

1nano ~/.bashrc

Now the SSH agent will start on each terminal session and you will only be prompted for the password on the first pull, push operation.

Use multiple SSH keys

If you have more than one GitHub account or if you have AWS code commit account then you will need to set up a config file, add your SSH key the same as detailed in How to authenticate with GitHub using SSH and give the key a different name:

1# ls ~/.ssh
2~/.ssh/id_rsa_github_1
3~/.ssh/id_rsa_github_2
4~/.ssh/id_rsa_git_aws

You can delete all cached keys before, with:

1ssh-add -D

You can check your saved keys, with:

1ssh-add -l

Set up the SSH config file, check to see if you haven’t got a config file already set up with:

1ls -al ~/.ssh/

If you haven’t got a config file there then:

1cd ~/.ssh/
2touch config

Use your text editor of choice, in this example we’ll use nano:

1nano config

Add your configuration:

1AddKeysToAgent yes
2
3# github_1 account
4Host github.com-github_1
5 HostName github.com
6 User git
7 IdentityFile ~/.ssh/id_rsa_github_1
8
9# github_2 account
10Host github.com-github_2
11 HostName github.com
12 User git
13 IdentityFile ~/.ssh/id_rsa_github_2
14
15# AWS code commit account
16Host git-codecommit.*.amazonaws.com
17 User AWSUSERNAME
18 IdentityFile ~/.ssh/id_rsa_git_aws

Clone your repo and modify the config file of the repo as detailed here: Specify multiple users for myself in .gitconfig?

There’s a great Gist detailing this here for more detail if needed.

Re-use SSH keys, from one machine to another

If you want to avoid creating multiple SSH keys for different environments and move your .ssh folder from one machine to another then you can do the following:

Copy your .ssh and .gitconfig files:

Copy from Linux to Windows

1cp ~/.ssh/* /c/Users/Scott.Spence/.linuxFiles/.ssh/
2cp ~/.gitconfig /c/Users/Scott.Spence/.linuxFiles/

Copy from Windows to Linux

1cp /mnt/c/Users/Scott.Spence/.linuxFiles/.ssh/* ~/.ssh/
2# Reset the permissions back to default:
3sudo chmod 600 ~/.ssh/id_rsa
4sudo chmod 600 ~/.ssh/id_rsa.pub
5cp /mnt/c/Users/Scott.Spence/.linuxFiles/.* ~/
6chmod 644 ~/.gitconfig

Start the SSH agent with:

1eval "$(ssh-agent -s)" # for mac and Linux from bash, also from Windows Git Bash

Add your SSH key to the ssh-agent with:

1ssh-add ~/.ssh/id_rsa

Then authenticate with:

1# GitHub
2ssh -T git@github.com
3# Bitbucket
4ssh -T git@bitbucket.org

Using SSH over the HTTPS port

SSH can be tunnelled over HTTPS if the network you are on blocks the SSH port.

Test if SSH over HTTPS is possible with:

1ssh -T -p 443 git@ssh.github.com

If you get a response then, edit your ~/.ssh/config file and add this section:

1Host github.com
2 Hostname ssh.github.com
3 Port 443

Check that you have a key already added with:

1ssh-add -l

If nothing is listed then add in your key with:

1ssh-add ~/.ssh/id_rsa

Test that is has worked with:

1ssh -T git@github.com

Change SSH key password

Tired of typing your SSH key password because you made it a 32 characters and can’t stand the manotoney anymore?

Still want to have a SSH key password on your existing SSH key?

Use:

1ssh-keygen -p -f ~/.ssh/id_rsa

Specify multiple users for myself in .gitconfig?

Want to have different git credentials for one specific repository?

You can configure an individual git repo to use a specific user/email address which overrides the global configuration.

To list out the config for the repo:

1git config --list --local

From the root of the repo, run:

1git config user.name 'Your Name'
2git config user.email 'your@email.com'

Whereas the default user / email is configured in your ~/.gitconfig

1git config --global user.name 'Your Name'
2git config --global user.email 'your@email.com'

Cant remember what your last git commit said?

1git show

Rebase changes

If you’re working on a team and there have been changes to the main branch you want to push your changes to, you can rebase before submitting a PR.

In this scenario we’re going to rebase our feature branch off of the develop branch

1# switch from your feature to get latest develop changes
2git checkout develop
3git pull
4# checkout the feature branch and rebase
5git checkout feature
6git rebase develop

Then use the prompts from there in conjunction with your text editor to add in the changes.

1# add a change
2git add
3# continue the rebase
4git rebase --continue
5# have an unrelated change, nothing to correct
6git rebase --skip
7# oh DERP! Want to start over?
8git rebase --abort

Rebase accept incoming in bulk

If you have a large file (like a package-lock.json) that you want to accept all the incoming changes from then.

Whilst you’re in rebase you’ll need to check out the file from your incoming branch then add it as the new file.

1# checkout the file
2git checkout temp-branch -- package-lock.json
3# add the file whilst in rebase
4git add package-lock.json
5# continue with the things
6git rebase --continue

See differences between two branches

If you want to see the difference between two branches then use the git built in diff tool.

1git diff branch1..branch2

See differences between two files

If you want to see the difference between two file across different branches then use.

1git diff branch1..branch2 package.json

Revert to a previous commit

Find the commit you want to revert to, then:

1git reset hashOfCommit

Then reset to the branch on the origin:

1# if I wanted to push back to the develop branch on GitHub say
2git reset --soft origin/develop

Reference: https://stackoverflow.com/questions/11829911/push-changes-without-pull

Gitignore

You can automate the creation of your projects gitignore file using the gitignore API.

Setup the API:

1git config --global alias.ignore \
2'!gi() { curl -sL https://www.gitignore.io/api/$@ ;}; gi'

Add to your shell configuration:

Bash

1echo "function gi() { curl -sL https://www.gitignore.io/api/$@ ;}" >> \
2~/.bashrc && source ~/.bashrc

checkout gi list for the languages and editors supported. You can issue the following command inside your project

1gi linux,visualstudiocode,node >> ./.gitignore

If you find yourself using the same .gitignore on your projects you can create a global file (i.e. .gitignore_global), and copy to your new project.

Reference: https://docs.gitignore.io/install/command-line