Back to Toolbox

Git recipes

List untracked files

From this Stack Overflow thread:

git ls-files --others --exclude-standard

Remove untracked files

git clean removes untracked files from the working tree. git clean -n (--dry-run) shows a preview of the effect, and git clean -f (--force) actually deletes them. Use -d to delete folders as well.

Bring in changes from another branch

git merge --squash my-feature brings in changes from the my-feature branch onto the current branch, without committing them.

Get the most recent tag that matches a pattern

git tag --sort=-creatordate --list "v-dev-*" | head -n1

Only lists tags matching the v-dev-* pattern (e.g. v-dev-0.1.0). With -creatordate we sort the tags in descending creation date. head -n1 picks up the first line from that output.

Delete remote tags that match a pattern

git tag | grep "v-dev-*" | xargs -n1 -I{} git push origin :{}

Clean up branches

Note: using git branch for scripts is brittle. It’s worth checking its output before running a destructive command.

To clean remote-tracking branches use:

git fetch --prune

See Pruning.

To get a list of local branches that relate to non-existing remotes, use git branch -vv and look for gone. Below using ripgrep:

git branch -vv | rg '^\s*([^\s]+).+: gone]' -or '$1'

You can pipe that output to git branch -D via xargs.

If you are absolutely sure you don’t have anything useful on your local branches, delete them all with:

git branch -l | xargs -L1 git branch -D