Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Git Cheatsheet

Using Git

Menu

Top commands | General | Global Settings | Setup | Reset | Update & Delete | Branch | Merge | Stash | Gitignore & Gitkeep | Log | Compare | Releases & Version Tags | Collaborate | Archive | Troubleshooting | Security | Large File Storage

Reminder

Show folder content: ls -la


Top commands

Status - show current branch and modified files git status [-s --short] or alias git st

Modify a specified commit git rebase --interactive 'bbc643cd^'

Tools:

gitk - shows history

gitk --all - shows history for all branches

git gui

git mergetool optional -t kdiff3

Aliases:

lg           # better 'log' show commits
logg         # better 'log' show commits
st = status
stats
co = checkout
ci = commit
ciam		# add + commit + message
cim 		# commit + message
amend  		# commit --amend --no-edit
br = branch
df = diff
dfs = diff --staged
dt = difftool
undo = reset --soft HEAD~1
stash-all = stash save --include-untracked
prune = fetch --prune #deletes any local branch which has been deleted from the remote

Stages all files: git add -A

Commit changes: git commit -m "Message"

Commit to most recent commit: git commit --amend -m "Message"

Pull: git pull for specific branch: git pull origin branchname

Push to default: git push origin master

Change to branch: git checkout branchname

Undo all changes (root directory): git checkout -- .

Undo latest commit SOFT: git reset --soft HEAD~

Undo latest commit HARD: git reset --hard <COMMIT -ID> or git reset --hard HEAD~<n>

git reset HEAD~ this leaves your working tree (the state of your files on disk) unchanged but undoes the commit and leaves the changes you committed unstaged (so they'll appear as "Changes not staged for commit" in git status, and you'll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message1, you could use git reset --soft HEAD~ instead, which is like git reset HEAD~ (where HEAD~ is the same as HEAD~1) but leaves your existing changes staged.

Add remote origin from GitHub project to existing local repository: git remote add origin https://github.com/user/project.git git remote -v

Create branch: git branch branchname

Update previous third commit message:

$ git log
$ git rebase -i HEAD~3 
change 'pick' to 'reword', ESC :wq
edit message (INSERT), ESC :wq

Merge to master

git checkout master
git pull origin master
git merge my_feature_branch_name
git push origin master

Merge to master (only if fast forward): git merge --ff-only my_feature_branch_name

Merge to master (force a new commit): git merge --no-ff my_feature_branch_name

Merge to master (force a new commit): git merge --no-ff --no-commit my_feature_branch_name

Stop merge (in case of conflicts): git merge --abort


General

Initialize Git: $ git init

Stages all files: $ git add -A

Stages new and modified, without deleted: $ git add .

Stages modified and deleted, without new: $ git add -u

Stage file: $ git add index.html

Undo all changes: git checkout -- .

Undo modifications (restore files from latest commited version): git checkout -- index.html

Commit changes: git commit -m "Message"

Add and commit in one step: git commit -am "Message"

Remove files from Git: git rm index.html

Remove files from Git - those ignored git rm -r --cached .

Update all changes: git add -u

Remove file but do not track anymore: git rm --cached index.html

Move or rename files: git mv index.html dir/index_new.html

Restore file from a custom commit (in current branch): git checkout 6eb715d -- index.html

Help: git help

Add remote origin from GitHub project to existing local repository:

git remote add origin https://github.com/user/project.git
git remote -v

Clone repository with certificates problem:

git -c http.sslVerify=false clone https://github.com/user/project.git
git config http.sslVerify false

Global Settings

Related Setup: https://gist.github.com/hofmannsven/6814278

Related Pro Tips: https://ochronus.com/git-tips-from-the-trenches/

Interactive Beginners Tutorial: http://try.github.io/

Setup

Installation:

  1. Use GIT from the Windows Command Prompt
  2. Checkout Windows-style, commit Unix-style line endings (core.autocrlf=true)
  3. Use MinTTY

See where Git is located: which git

Get the version of Git: git --version

$ git config --global user.email my@email.com
$ git config --global user.name my name kk

$ git config --global --add merge.tool kdiff3
$ git config --global --add mergetool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add mergetool.kdiff3.trustExitCode false

$ git config --global --add diff.guitool kdiff3
$ git config --global --add difftool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add difftool.kdiff3.trustExitCode false
$ git config --global --add difftool.prompt false

$ git config --global core.editor notepad2

$ git config --global status.showUntrackedFiles all
$ git config --global push.default tracking

Create an alias (shortcut) for git log advanced:

$ git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Set this configuration option for git push will by default push all branches that have the same name on the remote. To limit this behavior to just the current branch

$ git config --global push.default tracking

Create an alias (shortcut) for git status: git config --global alias.st status

Reset

This will unstage all files you might have staged with git add: git reset

This will revert all local uncommitted changes (should be executed in repo root): git checkout .

Undo all changes: git checkout -- .

You can also revert uncommitted changes only to particular file or directory: git checkout [some_dir|file.txt]

Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory): git reset --hard HEAD

Undo latest commit SOFT: git reset --soft HEAD~

Undo latest commit HARD: git reset --hard <COMMIT -ID> or git reset --hard HEAD~<n>

git reset HEAD~ this leaves your working tree (the state of your files on disk) unchanged but undoes the commit and leaves the changes you committed unstaged (so they'll appear as "Changes not staged for commit" in git status, and you'll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message1, you could use git reset --soft HEAD~ instead, which is like git reset HEAD~ (where HEAD~ is the same as HEAD~1) but leaves your existing changes staged.

This will remove all local untracked files, so only git tracked files remain: git clean -fdx Warning: -x will also remove all ignored files!

To sum it up: executing commands below is basically equivalent to fresh git clone from original source (but it does not re-download anything, so is much faster):

git reset
git checkout .
git clean -fdx

Undo interactive by selecting hunks: git checkout -p <file|.>

	y - discard this hunk from worktree
	n - do not discard this hunk from worktree
	q - quit; do not discard this hunk or any of the remaining ones
	a - discard this hunk and all later hunks in the file
	d - do not discard this hunk or any of the later hunks in the file
	g - select a hunk to go to
	/ - search for a hunk matching the given regex
	j - leave this hunk undecided, see next undecided hunk
	J - leave this hunk undecided, see next hunk
	k - leave this hunk undecided, see previous undecided hunk
	K - leave this hunk undecided, see previous hunk
	s - split the current hunk into smaller hunks
	e - manually edit the current hunk
	? - print help

Go back to commit: git revert 073791e7dd71b90daa853b2c5acc2c925f02dbc6

Soft reset (move HEAD only; neither staging nor working dir is changed): git reset --soft 073791e7dd71b90daa853b2c5acc2c925f02dbc6

Undo latest commit: git reset --soft HEAD~

Mixed reset (move HEAD and change staging to match repo; does not affect working dir): git reset --mixed 073791e7dd71b90daa853b2c5acc2c925f02dbc6

Hard reset (move HEAD and change staging dir and working dir to match repo): git reset --hard 073791e7dd71b90daa853b2c5acc2c925f02dbc6

Update & Delete

** Modify a specified commit: git rebase --interactive 'bbc643cd^'

Test-Delete untracked files: git clean -n

Delete untracked files (not staging): git clean -f

Unstage (undo adds): git reset HEAD index.html

Commit to most recent commit: git commit --amend -m "Message"

Update most recent commit message: git commit --amend -m "New Message"

Update previous third commit message:

$ git log
$ git rebase -i HEAD~3 
change 'pick' to 'reword', ESC :wq
edit message (INSERT), ESC :wq

Branch

Show branches: git branch [-v]

git branch -r - remotes

Create branch: git branch branchname

Get local copy of a remote branch:

git fetch
git checkout remote_branch_name

Change to branch: git checkout branchname

Create and change to new branch: git checkout -b branchname

Rename branch: git branch -m branchname new_branchname or: git branch --move branchname new_branchname

Show all completely merged branches with current branch: git branch --merged

Delete merged branch (only possible if not HEAD): git branch -d branchname or: git branch --delete branchname

Delete not merged branch: git branch -D branch_to_delete

Merge

True merge (fast forward): git merge branchname

Merge to master

git checkout master
git pull origin master
git merge my_feature_branch_name
git push origin master

Merge to master (only if fast forward): git merge --ff-only branchname

Merge to master (force a new commit): git merge --no-ff branchname

Stop merge (in case of conflicts): git merge --abort

Stop merge (in case of conflicts): git reset --merge // prior to v1.7.4

vimdiff instruction

Stash

Put in stash: git stash save "Message"

Put in stash and keep changes: git stash save --keep-index "Your Comment"

Show stash: git stash list

Show stash stats: git stash show stash@{0}

Show stash changes: git stash show -p stash@{0}

Use custom stash item and drop it: git stash pop stash@{0}

Use custom stash item and do not drop it: git stash apply stash@{0}

Delete custom stash item: git stash drop stash@{0}

Delete complete stash: git stash clear

Gitignore & Gitkeep

About: https://help.github.com/articles/ignoring-files

Useful templates: https://github.com/github/gitignore

Add or edit gitignore: nano .gitignore

Track empty dir: touch dir/.gitkeep

Log

Show commits: git log

Show oneline-summary of commits: git log --oneline

Show oneline-summary of commits with full SHA-1: git log --format=oneline

Show oneline-summary of the last three commits: git log --oneline -3

Show only custom commits: git log --author="Sven" git log --grep="Message" git log --until=2013-01-01 git log --since=2013-01-01

Show only custom data of commit: git log --format=short git log --format=full git log --format=fuller git log --format=email git log --format=raw

Show changes: git log -p

Show every commit since special commit for custom file only: git log 6eb715d.. index.html

Show changes of every commit since special commit for custom file only: git log -p 6eb715d.. index.html

Show stats and summary of commits: git log --stat --summary

Show history of commits as graph: git log --graph

Show history of commits as graph-summary: git log --oneline --graph --all --decorate

Compare

Compare modified files: git diff

Compare modified files and highlight changes only: git diff --color-words index.html

Compare modified files within the staging area: git diff --staged

Compare branches: git diff master..branchname

Compare branches like above: git diff --color-words master..branchname^

Compare commits: git diff 6eb715d git diff 6eb715d..HEAD git diff 6eb715d..537a09f

Compare commits of file: git diff 6eb715d index.html git diff 6eb715d..537a09f index.html

Compare without caring about spaces: git diff -b 6eb715d..HEAD or: git diff --ignore-space-change 6eb715d..HEAD

Compare without caring about all spaces: git diff -w 6eb715d..HEAD or: git diff --ignore-all-space 6eb715d..HEAD

Useful comparings: git diff --stat --summary 6eb715d..HEAD

Blame: git blame -L10,+1 index.html

Releases & Version Tags

Show all released versions: git tag

Show all released versions with comments: git tag -l -n1

Create release version: git tag v1.0.0

Create release version with comment: git tag -a v1.0.0 -m 'Message'

Checkout a specific release version: git checkout v1.0.0

Collaborate

Show remote: git remote

Show remote details: git remote -v

Add remote origin from GitHub project: git remote add origin https://github.com/user/project.git

Add remote origin from existing empty project on server: git remote add origin ssh://root@123.123.123.123/path/to/repository/.git

Remove origin: git remote rm origin

Show remote branches: git branch -r

Show all branches: git branch -a

Compare: git diff origin/master..master

Push (set default with -u): git push -u origin master

Push to default: git push origin master

Fetch: git fetch origin

Pull: git pull

Pull specific branch: git pull origin branchname

Merge fetched commits: git merge origin/master

Clone to localhost: git clone https://github.com/user/project.git or: git clone ssh://user@domain.com/~/dir/.git

Clone to localhost folder: git clone https://github.com/user/project.git ~/dir/folder

Clone specific branch to localhost: git clone -b branchname https://github.com/user/project.git

Delete remote branch (push nothing): git push origin :branchname or: git push origin --delete branchname

Pushing to multiple git repos (remotes)

link

git remote set-url --add --push origin https://github.com/USER_NAME/REPO_NAME.git
git remote set-url --add --push origin https://USER_NAME@bitbucket.org/USER_NAME/REPO_NAME.git
git remote set-url --add --push origin https://gitlab.com/USER_NAME/REPO_NAME.git
git remote set-url --add --push origin https://USER_NAME.visualstudio.com/_git/REPO_NAME

Result .\git\config file:

[remote "origin"]
	url = https://github.com/USER_NAME/REPO_NAME.git
	fetch = +refs/heads/*:refs/remotes/origin/*
	pushurl = https://github.com/USER_NAME/REPO_NAME.git
	pushurl = https://USER_NAME@bitbucket.org/USER_NAME/REPO_NAME.git
	pushurl = https://gitlab.com/USER_NAME/REPO_NAME.git
	pushurl = https://USER_NAME.visualstudio.com/_git/REPO_NAME

Archive

Create a zip-archive: git archive --format zip --output filename.zip master

Export/write custom log to a file: git log --author=sven --all > log.txt

Troubleshooting

Ignore files that have already been committed to a Git repository: http://stackoverflow.com/a/1139797/1815847

Security

Hide Git on the web via .htaccess: RedirectMatch 404 /\.git (more info here: http://stackoverflow.com/a/17916515/1815847)

Large File Storage

Website: https://git-lfs.github.com/

Install: brew install git-lfs

Track *.psd files: git lfs track "*.psd" (init, add, commit and push as written above)

Show full configuration git config --list --show-origin

git config --global -e for edit

type %HOME%\.gitconfig or cat %HOME%\.gitconfig

vim %HOME%\.gitconfig then press P for paste

C:\Users\USER_NAME\.gitconfig

[user]
	email = myemail@gmail.com
	name = my user name
[core]
	autocrlf = true
	excludesfile = C:\\Users\\USER_NAME\\Documents\\gitignore_global.txt
	editor = notepad
	#editor = "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
	
[status]
  showUntrackedFiles = all
  # Sometimes a newly-added folder, since it's only one line in git status, can slip under the radar.

#[merge]
#	tool = kdiff3
#[diff]
#	guitool = kdiff3
[difftool]
  	prompt = false

[mergetool "kdiff3"]
	path = C:/Program Files/KDiff3/kdiff3.exe
	trustExitCode = false
	keepBackup = false
[difftool "kdiff3"]
	path = C:/Program Files/KDiff3/kdiff3.exe
	trustExitCode = false
	
[mergetool "meld"]
	path = C:/Program Files (x86)/Meld/Meld.exe
	trustExitCode = false
	keepBackup = false
[difftool "meld"]
	path = C:/Program Files (x86)/Meld/Meld.exe
	trustExitCode = false
	
[mergetool "p4merge"]
	path = C:\\Program Files\\Perforce\\p4merge.exe
[difftool "p4merge"]
	path = C:\\Program Files\\Perforce\\p4merge.exe

[difftool "tortoise"]
    cmd = \""C:/Program Files/TortoiseGit/bin/TortoiseGitMerge.exe"\" -mine:"$REMOTE" -base:"$LOCAL"
[mergetool "tortoise"]
    cmd = \""C:/Program Files/TortoiseGit/bin/TortoiseGitMerge.exe"\" -base:"$BASE" -theris:"$REMOTE" -mine:"$LOCAL" -merged:"$MERGED"

[difftool "vscode"]
    cmd = code --new-window --wait --diff $LOCAL $REMOTE
    
[push]
	default = tracking

	#default = simple
  		# "push the current branch back to the branch whose changes are usually integrated into the current branch"
  		# "refuse to push if the upstream branch’s name is different from the local one"
[alias]
    lgg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    lg = !git lgg -10
    co = checkout
    st = status
    ci = commit
    ciam = "!f() { git add -A && git commit -m \"$@\"; }; f"
    cim = "!f() { git commit -m \"$@\"; }; f"
    amend = commit --amend --no-edit
    br = branch
    pl = pull --ff-only
    plr = pull --rebase
    df = diff
    dfs = diff --staged
    dt = difftool
    dtdm = difftool -t diffmerge
    dtp = difftool -t p4merge
    dtk = difftool -t kdiff3
    dtc = difftool -t vscode
    dtt = difftool -t tortoise
    mtdm = mergetool -t diffmerge
    mtp = mergetool -t p4merge
    mtk = mergetool -t kdiff3
    mtc = mergetool -t vscode
    mtt = mergetool -t tortoisemerge
    logg = log --graph --decorate --oneline --abbrev-commit --all
    stats = log -10 --dirstat=files,1,cumulative --ignore-blank-lines --abbrev-commit --oneline --graph --decorate
    prune = fetch --prune 
  	undo = reset --soft HEAD~1
    stash-all = stash save --include-untracked 
		#deletes any local branch which has been deleted from the remote
[http]
	sslVerify = true
[credential]
# helper = manager
# helper = wincred
[credential "helperselector"]
selected = <
[user]
name = My name
email = myname@gmail.com
[core]
autocrlf = true
editor = notepad
[status]
showUntrackedFiles = all
[push]
# default = tracking
default = current
[difftool "WinMerge"]
cmd = \"C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe\" -e -u -dl \"Old $BASE\" -dr \"New $BASE\" \"$LOCAL\" \"$REMOTE\"
trustExitCode = true
[mergetool "WinMerge"]
cmd = \"C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe\" -e -u -dl \"Local\" -dm \"Base\" -dr \"Remote\" \"$LOCAL\" \"$BASE\" \"$REMOTE\" -o \"$MERGED\"
trustExitCode = true
keepBackup = false
[alias]
alias-ls = !git config --get-regexp alias
lgg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
lg = !git lgg -10
co = checkout
st = status
stt = status -sb # smarter status - include tag and branch info
stm = status -sb # smarter status - include tag and branch info
cfg = config -e --global
mm = merge master
cm = checkout master
cmp = !git checkout master && git pull master
ci = commit
ciam = "!f() { git add -A && git commit -m \"$@\"; }; f"
cim = "!f() { git commit -m \"$@\"; }; f"
amend = commit --amend --no-edit
br = branch
pl = pull --ff-only
plr = pull --rebase
df = diff --word-diff
dfs = diff --staged
dfw = diff --word-diff
dt = difftool
dtw = difftool -t WinMerge
mtw = mergetool -t WinMerge
remove-untracked = !git fetch --prune && git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d
logg = log --graph --decorate --oneline --abbrev-commit --all
stats = log -10 --dirstat=files,1,cumulative --ignore-blank-lines --abbrev-commit --oneline --graph --decorate
prune = fetch --prune
undo = reset --soft HEAD~1
stash-all = stash save --include-untracked
recentbr = branch --sort=-committerdate --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
ls = log --pretty=format:'%C(yellow)%h -%C(blue)%ad%C(red)%d -%C(reset)%s%C(green) [%cn]' --decorate --date=short # pretty one-line log with tags, branches and authors
lsv = log --pretty=format:'%C(yellow)%h %C(blue)%ad%C(red)%d -%C(reset)%s%C(green) [%cn]' --decorate --date=short --numstat # a verbose ls, shows changed files too
# some resets without explanation
r = reset
r1 = reset HEAD^
r2 = reset HEAD^^
rh = reset --hard
rh1 = reset HEAD^ --hard
rh2 = reset HEAD^^ --hard
[pull]
rebase = false

git config --global --list

user.email=myemail@gmail.com
user.name=my user name
core.autocrlf=true
core.excludesfile=C:\Users\USER_NAME\Documents\gitignore_global.txt
core.editor=notepad
status.showuntrackedfiles=all
difftool.diffmerge.cmd='C:/Program Files/SourceGear/Common/DiffMerge/sgdm.exe' $LOCAL $REMOTE
mergetool.diffmerge.trustexitcode=true
mergetool.diffmerge.cmd='C:/Program Files/SourceGear/Common/DiffMerge/sgdm.exe' -merge -result=$MERGED $LOCAL $BASE $REMOTE
difftool.kdiff3.path=C:/Program Files/KDiff3/kdiff3.exe
mergetool.p4merge.path=C:\Program Files\Perforce\p4merge.exe
difftool.p4merge.path=C:\Program Files\Perforce\p4merge.exe
difftool.vscode.cmd=code --new-window --wait --diff $LOCAL $REMOTE
difftool.tortoise.cmd="C:/Program Files/TortoiseGit/bin/TortoiseGitMerge.exe" -mine:$REMOTE -base:$LOCAL
push.default=tracking
http.sslverify=true
alias.lgg=log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
alias.lg=!git lgg -10
alias.co=checkout
alias.st=status
alias.ci=commit
alias.ciam=!f() { git add -A && git commit -m "$@"; }; f
alias.cim=!f() { git commit -m "$@"; }; f
alias.amend=commit --amend --no-edit
alias.br=branch
alias.pl=pull --ff-only
alias.plr=pull --rebase
alias.df=diff
alias.dfs=diff --staged
alias.dt=difftool
alias.dtdm=difftool -t diffmerge
alias.dtp=difftool -t p4merge
alias.dtk=difftool -t kdiff3
alias.dtc=difftool -t vscode
alias.dtt=difftool -t tortoise
alias.mtdm=mergetool -t diffmerge
alias.mtp=mergetool -t p4merge
alias.mtk=mergetool -t kdiff3
alias.mtc=mergetool -t vscode
alias.mtt=mergetool -t tortoisemerge
alias.logg=log --graph --decorate --oneline --abbrev-commit --all
alias.stats=log -10 --dirstat=files,1,cumulative --ignore-blank-lines --abbrev-commit --oneline --graph --decorate
alias.prune=fetch --prune
alias.undo=reset --soft HEAD~1
alias.stash-all=stash save --include-untracked
gui.fontdiff=-family Consolas -size 10 -weight normal -slant roman -underline 0 -overstrike 0
λ cd C:\GitDemos\GitDemo
λ git init
λ notepad a.txt 
λ notepad b.txt 
λ git status
λ git add . 
λ git status
λ git commit -am "files created" 
λ git log

#CREATE 'remote' git on another disk
#-----------------------------------
λ D:
λ cd _DEV\_gitrepos\GitDemo-origin\
λ git init --bare GitDemo.git
#-----------------------------------

λ git remote add origin D:\_DEV\_gitrepos\GitDemo-origin\GitDemo.git 
λ git push origin master
λ git branch -u origin/master

#CLONE NEW REPOSITORY
#-----------------2nd repository
λ cd ..
λ git clone  D:\_DEV\_gitrepos\GitDemo-origin\GitDemo.git GitDemo2
λ cd GitDemo2
# show history
λ gitk

#-----------------1st repository
λ cd ..\GitDemo
λ notepad a.txt
λ git st
λ git add .
λ git commit -m "a.txt modified with some text"
λ git push
#-----------------2nd repository
λ cd ..\GitDemo2
λ git pull

#-----------------1st repository
λ cd ..\GitDemo
λ git branch conflict-branch
λ git checkout conflict-branch
λ notepad b.txt
λ git commit -am "conflict change added to b.txt" 
λ git checkout master
λ git merge conflict-branch
λ git mergetool -t kdiff3
λ git commit -m "merge conflict change" 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment