Git commands

A list of some key Git commands for quick reference:
ActionCommand 
Create a new branch and switch to it.git checkout -b [branch-name]
Push a local branch to remote.git push -u origin [branch-name]
Apply changes in a feature branch to the master branch.
  • git checkout master
  • git merge [branch-name]
Apply changes in the master branch to a feature branch.
  • git checkout [branch-name]
  • git merge master
Abort merge (with conflicts).git merge --abort
List all local branches.git branch
List all remote branches.git branch -r
List all remote and local branches.git branch -a
Show the difference between two branches.git diff [branch-1-name] [branch-2-name]
Rename a local branch.git branch -m [branch-name] [new-branch-name]
Delete a local branch.git branch -d [branch-name]
Remove references to deleted remote branches.git fetch --all --prune
Reset a local branch to the state of the remote branch.git reset --hard origin/[branch-name]
Undo changes to all files.git checkout .
Undo changes to a specified file.git checkout [file]
Stage the changes to all files.git add .
Undo staging of all files i.e. the last 'git add .' command.git reset
Undo staging of a specified file.git reset [file]
Commit the changes to all files with a messagegit commit -m "[Commit message]"
Edit the most recent commit message
  • git commit --amend -m "[New commit message]" Note: Any staged changes will also be committed.
Undo last 'git commit' command.git reset --soft HEAD~1
View commit history.git log
View all reference logs - Commits, resets and merges.git reflog
Save and stash current changes with a message.git stash push -m "[stash-message]"
Save and stash changes to a specified file.git stash push -m "[stash-message]" [file]
Apply a stash by index but leave in stash list.git stash apply stash@{[stash-index]}
Apply a stash by index and remove from stash list.git stash pop stash@{[stash-index]}
Remove stash from list by index.git stash drop stash@{[stash-index]}
Clear all stashes.git stash clear
Push master to newly created remote repo.git push --set-upstream [remote-repo-url] master
Clean commit history.
  • rm -rf .git
  • git init
  • git add .
  • git commit -m "[New commit message]"
Combine a number of commits (N) into one commit.
  • git rebase -i HEAD~[N] The editor will open with a list of the last N commits marked with 'pick'.
  • Replace 'pick' with 'squash' or 's' on all except the first of the listed commits.
  • Save and quit the editor. The editor will open with the commit messages of all the squashed commits, delete all commit messages and enter a new message
  • Save and quit the editor.