find branch name during git rebase

Although git branch --list shows a branch name (see this answer for the details), it is not useful during the scripting as you need to parse the output.

I use the following function to get a branch name (based on head-name file):

rebasing-branch() {
    for location in rebase-merge rebase-apply; do
        path=$(git rev-parse --git-path ${location})
        if test -d ${path}; then
            revision=$(<${path}/head-name)
            echo ${revision##refs/heads/}
            return 0
        fi
    done
}

It shows the branch name during either regular or interactive rebase.


Is there a way to find the name of the branch-being-rebased during an interactive rebase, that is better than parsing .git/rebase-merge/head-name?

Note that with Git 2.18 (Q2 2018), "git branch --list" during an interrupted "rebase -i" now lets users distinguish the case where a detached HEAD is being rebased and a normal branch is being rebased.

So you still need to parse, but the output of the command itself is now useful.

See commit 1f537be (03 Apr 2018) by Eric Sunshine (sunshineco).
See commit a236f90 (03 Apr 2018) by Kaartic Sivaraam (sivaraam).
(Merged by Junio C Hamano -- gitster -- in commit 4cbaa6b, 25 Apr 2018)

branch --list: print useful info whilst interactive rebasing a detached HEAD

When rebasing interactively (rebase -i), "git branch --list" prints a line indicating the current branch being rebased.
This works well when the interactive rebase is initiated when a local branch is checked out.

This doesn't play well when the rebase is initiated on a detached HEAD.
When "git branch --list" tries to print information related to the interactive rebase in this case it tries to print the name of a branch using an uninitialized variable and thus tries to print a "null pointer string".
As a consequence, it does not provide useful information while also inducing undefined behaviour.

So, print the point from which the rebase was started when interactive rebasing a detached HEAD.

See the test.