I often find myself wanting to reference the current branch I am on when typing a command. I create a bash function to paste it.

When wanting to push a branch to a remote one often finds they need to reference it, i.e.:

$ git push origin mf/foobar:mf/foobar

or even:

$ git push origin mf/foobar:demo/mf/foobar

I do this so often I’ve decided enough was enough, and created a function and a binding to make it easier to perform this operation multiple times.

This is “it” in Bash: append it somewhere in your ~/.bashrc:

paste-current-git-branch() {
    local selected
    selected="$( git rev-parse --abbrev-ref HEAD )"
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$selected${READLINE_LINE:$READLINE_POINT}"
    READLINE_POINT=$(( READLINE_POINT + ${#selected} ))
}
bind -x '"\C-b": "paste-current-git-branch"'

I bound its use to CTRL+B.

Mnemonic: b for branch

This is the same for Zsh - stick it in your ~/.zshrc or similar:

if [[ $- == *i* ]]; then
    # CTRL-B - Paste the current branch
    git-currentbranch-paste() {
        LBUFFER="$LBUFFER$(git rev-parse --abbrev-ref HEAD)"
        local ret=$?
        zle redisplay
        typeset -f zle-line-init >/dev/null && zle zle-line-init
        return $ret
    }
    zle     -N   git-currentbranch-paste
    bindkey '^B' git-currentbranch-paste
fi

Now, all I have to do is:

$ git push origin CTRL+b:CTRL+b

or:

$ git push origin CTRL+b:demo/CTRL+b