Git Tips and Tricks


Some useful commands

Setup git to use vscode has the default editor

Run this command and then add this lines:

$ git config --global -e
	editor = code --wait

	tool = default-difftool

[difftool "default-difftool"]
  cmd = code --wait --diff $LOCAL $REMOTE

	prompt = false

	tool = code

[merge "tool"]
	cmd = "code --wait $MERGED"
	prompt = false
	keepbackup = false

How to compare (diff) files from two different branches

git difftool mybranch anotherbranch -- myfile.txt


git diff branch1:file branch2:file

commit –amend

Edit a commit before push it, example:

$ touch test.txt
$ git add test.txt
$ git commit -m "Test file"
[master 964fa35] Test file
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 test.txt
$ git log --oneline
964fa35 (HEAD -> master)Test file
$ touch test2.txt
$ git add test2.txt 
$ git commit --amend -m "Test and Test2 file"
$ git log --oneline
414a06e (HEAD -> master) test and test2

git log

git log shows the current HEAD and its ancestry. That is, it prints the commit HEAD points to, then its parent, its parent, and so on.

$ git log --oneline
$ git log HEAD@{1.hour.ago}
$ git log HEAD@{1.week.ago}

git reflog

git reflog doesn’t traverse HEAD’s ancestry at all. The reflog is an ordered list of the commits that HEAD has pointed to: it’s undo history for your repo. The reflog isn’t part of the repo itself (it’s stored separately to the commits themselves) and isn’t included in pushes, fetches or clones; it’s purely local.

$ git reflog HEAD@{1.hour.ago} --oneline

How to clear unreachable commits

$ git reflog expire --expire-unreachable=now --all
$ git gc --prune=now

Leave a Reply

Your email address will not be published. Required fields are marked *