Published 18/05/2023
Last Updated 21/11/2024

Config

# set user name and email that will be associated with version history
git config --global user.name "John Doe"
git config --global user.email "[email protected]"

# set automatic command line coloring for Git for easy reviewing
git config --global color.ui auto

# config alias & common alias config
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --' # unstage a file
git config --global alias.last 'log -1 HEAD' # show last commit

See more at https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

Create

# create a new local repository
git init

# clone an existing repository
git clone <url>

Branches & Tags

# list all branches, a * will appear next to the currently active branch
git branch
# list all branches with keyword
git branch | grep <keyword>

# create a new branch
git branch <branch>
# create a new branch and check it out into your working directory
git checkout -b <branch>

# create a new tracking branch based on a remote branch
git checkout --track <remote>/<branch>
# or
git branch --track <branch> <remote>/<branch>

# change current branch name
git branch -m <newname>

# delete the specified branch
git branch -d <branch>

# switch to another branch and check it out into your working directory
git checkout <branch>
# switch to previous active branch
git checkout -

# merge the specified branch’s history into the current one
git merge <branch>

# mark the current commit with a tag
git tag <tag>

Branch names should follow a convention. Read more at:

Stage & Commit

File status lifecycle:

https://git-scm.com/book/en/v2/images/lifecycle.png

stage

# show the status of the working directory and staging area
git status

# add the specified file to the staging area
git add <file>

# add all files to the staging area
git add .

# add all files to the staging area and remove all deleted files
git add -A

# unstage the specified file
git reset <file>

# unstage all files
git reset

# undo changes of the specified file (not staged)
git checkout <file>

# undo changes of all files (not staged)
git checkout .

diff

git diff show differences between the working directory, the staging area, and the

most recent commit:

# show differences between the working directory and the most recent commit
git diff

# show differences between the staging area and the most recent commit
git diff --staged # or
git diff --cached

# show differences between the working directory and staging area versus the
# most recent commit
git diff HEAD

# show differences between the specified commit and the most recent commit
git diff <commit>

# show diff with stats
git diff --stat

# only display the names of changed files
git diff --name-only