Git Cheat Sheet

 

Create new repository

Create a new repository on the command line

git init
git branch -M main
git add .
git commit -m "first commit"
git remote add origin git@github.com:username/repo-name.git
git push -u origin main

Push an existing repository from the command line

git branch -M main
git remote add origin git@github.com:username/repo-name.git
git push -u origin main

Branch

Basic usage

List branches:

git branch

Create a new branch:

git branch <branch>

Switch to an existing branch:

git switch <existing-branch>

Create a new branch and switch to it:

git switch -c <new-branch>

Create a new branch based on <existing-branch> instead of current HEAD:

git switch -c <new-branch> <existing-branch>

Delete and force delete a branch:

git branch -d <branch>
git branch -D <branch>

Rename the current branch to <branch>:

git branch -m <branch>

List all remote branches:

git branch -a

Remote Control

Add remote repository <remote-repo> to local repository config:

git remote add <remote-repo> https://github.com/user/repo.git

Push the <new-branch> branch to <remote-repo> and set upstream tracking:

git push -u <remote-repo> <new-branch>

Delete branch <new-branch> from remote repository:

git push origin --delete <new-branch>

Check out a remote branch:

git switch --track origin/<remote-branch>