Skip to main content

Uncommon but useful Git commands

ยท 2 min read

This is a cheatsheet for useful Git commands that we use semi-regularly, mostly for internal use as a quick future reference but I figured I would share.

Change commit author dateโ€‹

git commit --amend --no-edit --date="Wed Mar 30 22:45:55 2022 +0200"

Get last commit to modify fileโ€‹

git log -n 1 --format="%H %s" -- path/to/file

Get first commitโ€‹

git log --reverse --format="%H %s" | head -1

Find commits with modified code matching some stringโ€‹

git log --branches -S'some code you need to fix'

Find commits with modified code matching some regular expressionโ€‹

git log --branches -G'some code you need to fix'

Create a commit message with a trailerโ€‹

git commit -am 'add something' --trailer="Molecule: apiPackageManager=NPM, apiLanguage=TypeScript"

Find dangling commitsโ€‹

git fsck --lost-found 2>&1 | grep "dangling commit"

Wipe unused historyโ€‹

git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin
git reflog expire --expire=now --expire-unreachable=now --all
git gc --prune=now --aggressive

Remove untracked files and directoriesโ€‹

git clean -f -d

Delete all remote branches:โ€‹

git branch -r | grep origin/ | grep -v 'index$' | grep -v HEAD| cut -d/ -f2 | while read line; do git push origin :$line; done;