Git tips and tricks

Checking if anything outstanding in repo

[[ -z $(git status --porcelain) ]] && echo "do nix" || echo "do summink"

Git create local branch from remote

git checkout -b <BRANCH> origin/<BRANCH>

Git interactive rebase the first commit

One small frustration with git is the inability to do an interactive rebase on the first commit. More recent versions have this ability using the additional --root switch:

git rebase -i --root

List all files already committed and being tracked

git ls-tree --full-tree -r HEAD # or instead of HEAD, the commit hash or branch name
git ls-tree -r master --name-only
git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

List all files in a commit

git diff-tree --no-commit-id --name-only -r HASH

or

git show --pretty="" --name-only HASH

For a full explanation see this posting


List branches ahead or behind remote

git branch -v | grep -E 'ahead|behind' | sed -r 's/[ *]\s(\S*).*(\[(ahead|behind).+?\]).*/\1 \2/g'

See reference.


List branches sorted by latest commit

git for-each-ref --sort=-committerdate refs/heads/

See reference.


Pretty-print tree-like view in terminal

Most useful is

git log --graph --all --decorate --pretty=oneline --abbrev-commit

showing, e.g.

67075f012acb501278bbc169e5c4cdbd.png

Other varieties:

git log --graph --oneline --all
git log --graph --oneline --all --decorate
git log --graph --decorate --pretty=oneline --abbrev-commit

Show differences between current version and last commit

git diff HEAD^ HEAD

See this reference.


Show diffs between branches

git diff master..staging

Show the contents ‘cat’ of a file in git

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py

See this reference.


Undo ‘git add’ or remove file(s) from staging area

i.e. remove a file from git index but not the working tree.

For a single file

git reset <file>

But also

git reset

without any file name will unstage all changes.

See reference.


Update local repository from remote

Safe! Updates local copies of remote branches but does not update (=overwrite) local branches

git remote update

equivalent to

git fetch --all

Using a remote repository with a non-standard port

Based on this tip, create or add the following to your ~/.ssh/config file:

Host githost
HostName example.com
Port 7654
User felix

Then the normal git syntax should work, e.g.

git push origin dev