This is a reminder post for myself to remember the most useful git commands.
Commands changing the local history
- Undo last commit and stage changes:
git reset --soft HEAD^
- Permanently delete last commit :
git reset --hard HEAD^
HEAD^^for the last two commits,
HEAD^^^for the last three commits, … Use HEAD~<number> to reference the commit
Note: Do NOT use any of these commands after pushing to a repository as this would alter (the) history!
Merges and branches
git checkout -b <branch name>to create a new branch and automatically check the branch out.
- Deleting branches using
git branch -d <name>will not work when commits are unreachable after this. Use
- Invoke merge commands from the branch you want to merge into, e.g., from master to merge feature_branch into master. (
git merge feature_branchin master branch) After merging a branch, it can be safely deleted.
Remotes and remote branches
git pushsets the passed remote and branch name as the default for the current repository. (
git push [-u] <remote name> <local branch>)
git push <remove name> :<remote branch>deletes the remote branch. The colon marks the branch for deletion.
git remote show <remote name>displays lots of information about this remote.
git remote prune <remove name>deletes all local branches which do not have any corresponding remote branches anymore.
git taglists all tags.
git checkout <tag name>checks out the commit referenced by the tag.
git tag -a <tag name> -m "<tag description>"adds a new tag.
git push --tagspushes the tags to the default remote.
- HEAD represents the local version in any conflict marking.
- When using feature branches, first, run
git rebaseon feature branch and then
git mergeusing fast forward in the master branch. This ensures that the possible conflict merges are made in the feature branch and not in the master branch.
- Merge is better then rebase when the branches diverged by many (really many) commits.
Additional notes to myself
- Use git aliases with
git config alias.<abbreviation> "<full version>"!
git blame <file>displays which line of the given file has been authored by which user at which time in which commit.
Which commands do you consider useful?