My favorite custom git commands - Phelipe Teles

My favorite custom git commands

2 min.
View source code

In this post I want to share my favorite custom git commands — from aliases to shell scripts.

git recent

git recent is an alias to list the most recent branches:

[No name]
[alias]  recent = branch -v --sort=-committerdate

It works by listing branches sorted by commit date, in descending order.

git undo

git undo is an alias to undo the last commit:

[No name]
[alias]  undo = reset --soft HEAD^

It works by using the git reset command, which will make the tip of the branch point to a specific git revision (a commit reference).

Our goal is to undo the last commit, so we need a revision to the commit before the current one, which is what HEAD^ means.

The --soft option is to keep the undone commit’s changes in the staging area.

I often use this command when rebasing, e.g. to remove a file from a commit or to split commits.

The undo name may be misleading, since it’s not a general purpose undo like the one from git-branchless — it’s a lot simpler.

git recommit

git recommit is an alias I use to make a commit while reusing the undone commit’s message.

[No name]
[alias]  recommit = commit --reedit-message ORIG_HEAD

It works by using the symbolic ref name ORIG_HEAD, described by man gitrevisions as:

ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation […].

git reset is one of such commands that “move your HEAD in a drastic way”. That’s why I often it after git undo.

git spinoff

You know when you’re working on a feature for a while, and later realize that committed into main the whole time?

Magit has a command to help you with this, called magit-branch-spinoff.

This command creates and checks out a new branch starting at and tracking the current branch. That branch in turn is reset to the last commit it shares with its upstream. […] This is useful to create a feature branch after work has already began on the old branch (likely but not necessarily “master”).

But for those of us that don’t use Emacs, there’s git-toolbelt, a collection of git-related shell scripts, including git spinoff!

Its API is similar to git checkout -b, i.e. you need to pass the name of the new branch (and an optional base — usually it’ll be main).

[No name]
usage: git spinoff [-h] <new-name> [<base>]

git cb

git cb is a script that combines fzf and git recent to give a nice interface to change branches.

bash
#!/bin/bashset -eu branch=$(git recent --format '%(refname:short)' | fzf --height 40% --preview 'git log --oneline {}') if [[ -n "$branch" ]]; then  git checkout "$branch"fi

It’s a good idea to combine fzf with git when a workflow requires you to select a commit from a list.

The script git-cb running in the terminal