Skip to content

Instantly share code, notes, and snippets.

@raduserbanescu
Last active January 10, 2018 15:44
Show Gist options
  • Save raduserbanescu/b29e39ef1625eae636366872db48177b to your computer and use it in GitHub Desktop.
Save raduserbanescu/b29e39ef1625eae636366872db48177b to your computer and use it in GitHub Desktop.
A collection of useful git commands (that I can never remember) and some tips & tricks

Useful git commands

log

Limit the number of commits to output

git log -3

Draw a text-based graphical representation of the commit history

Current branch

git log --graph --oneline --decorate

All branches

git log --graph --oneline --decorate --all

Show diff output for a merge commit

  • -c: shows the differences from each of the parents to the merge result simultaneously. Furthermore, it lists only files which were modified from all parents.
  • --cc: implies the -c option and further compresses the patch output by omitting uninteresting hunks whose contents in the parents have only two variants and the merge result picks one of them without modification
  • -m: show the full diff like regular commits; for each merge parent, a separate log entry and diff is generated

Reference: Diff Formatting

List commits from a merged topic branch

git log MERGE_COMMIT^..MERGE_COMMIT^2

Reference: Git revisions and ranges

diff

Show multiple lines of context instead of the usual three

git diff -U10

push

Force

Do a force push, but refuse if the remote branch has been updated by somebody else.

git push --force-with-lease

Delete remote reference (branch, tag)

git push --delete origin REF_NAME

clean

Remove untracked files from the working tree.

git clean
  • -n: dry run (just show what would be done)
  • -f: actually remove files (by default git would refuse without this option)
  • -d: also remove directories
  • -x: also remove ignored files
  • -X: remove only ignored files, but keep untracked files

reset

Overwrite local branch with remote ("force pull")

⚠️ All local commits and changes will be lost.
🆗 Any untracked files will not be affected.

git fetch origin BRANCH_NAME
git reset --hard origin/BRANCH_NAME

If you want to also remove untracked files, run a git clean.

Reference: How do I force “git pull” to overwrite local files?

Notes

Creating custom scripts

When you need to parse Git data inside a custom script, you should use Git low-level commands (plumbing) instead of the main ones (porcelain).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment