[GUIDE] Git commands cheat sheet

[GUIDE] Git commands cheat sheet header image
FEB07

This cheat sheet contains git commands, almost every developer use on daily basis. They will save you a lot of time and nerves.

Create new git repository

(don't forget to add appropriate .gitignore file to the root of the project beforehand)

git init
git add .
git commit -m "Initial commit"

Staging

Stage all files to commit

git add -A

Stage all changed files and commit (new files are ignored)

git commit -a -m "Commit message"

Revert changes to modified files

git reset --hard

Remove all untracked files and directories

git clean -fd

Tags

Add a tag

git tag -a v0.5 -m 'Version 0.5 Stable'

Add a tag to older commit

git tag -a 1.0.1 commit_id -m 'Version 1.0.1'

Push all tags to remote repository

git push --tags

Switch to tag

git checkout tag_name

Delete local tag

git tag -d v.0.4

Delete remote tag

git push origin :v0.4

Branches

List all local branches

git branch

List all remote branches

git branch -r

List all local and remote branches

git branch -a

Create branch from current

git branch branch_name

Create branch and switch to it

git checkout -b branch_name

Create branch from commit

git branch branch_name commit_id

Create branch from commit and switch to it

git checkout -b branch_name commit_id

Merge branch_name into current branch

git merge branch_name

Delete local branch

git branch -D branch_name

Delete remote branch

git push origin --delete branch_name

or after deleting local branch:

git push origin :branch_name

Rename branch

git branch -m oldname newname
git push origin :oldname
git push origin newname

Remove local branches according to deleted remote ones

git fetch -p

Update local repository according to state of remote

git remote update origin --prune

Merging

git merge branch_name

Fetch changes from remote repository and apply them locally

git fetch origin
git reset --hard origin/master

Discard changes in a file

git checkout v1.2.3 -- filename         # tag v1.2.3
git checkout stable -- filename         # stable branch
git checkout origin/master -- filename  # upstream master
git checkout HEAD -- filename           # the version from the most recent commit
git checkout HEAD^ -- filename          # the version before the most recent commit

Remove all previously commited files that are in .gitignore now

git rm --cached git ls-files -i --exclude-standard

or

git rm --cached git ls-files -i --exclude-from=.gitignore

Thanks for reading! This article should help you on daily basis when you are just starting out with git.

P.S. This article is internal App Dev Academy guide and will be constantly updated with changes required for existing and future projects.