Git useful commands

Repositories

List remote repositories

git remote -v

Add new remote repository

git remote add <REMOTE_REPO_NAME> https://github.com/<OWNER>/<REPOSITORY>.git

In case of fork, it’s useful to add the original repo as a remote repo named ‘upstream’

git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git

Sync fork repo with original repo

First, fetch original repo

git fetch upstream

Then, switch to fork/branch to sync with original branch (eg. master)

git checkout master

Merge original/branch with fork/branch

git merge upstream/master

Finally, push synced fork/branch in remote fork/repo (eg. master)

git push origin master

Branches

List Branches

only local branches

git branch

both remote-tracking and local branches

git branch -a

Create new branch and switch to new Branch

git checkout -b <branch_name>

Clone a specific Branch

Create local Branch linked to remote Branch

Switch Branch

git checkout <branch_name>

Remove Branch

Remove local branch

git branch -d <branch_name>

Remove remote branch once removed local branch

git push origin :<branch_name>

Push changes to Branch

git push origin <branch_name>

Merge Branches

switch to destination branch
than commit selected branch into current branch
--no-ff option generate a merge commit with a message
git merge --no-ff <branch_name>

Tags

List Tags

git tag

Create Tag

Push Tag

Push all tags

git push --tags

Push a single tag

git push origin <tag_name>

Undo

Discharge changes on file or restore deleted file

Undo a commit

TIPS

After fetching, remove any remote-tracking branches which no longer exist on the remote.

git fetch --prune

Create a local branch named xxx, tracking the remote branch origin/xxx

git checkout --track origin/xxx