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;