Search code examples
gitbranch

Can git branches be listed with numbers?


I was wondering if anyone had built a script or had a way to list git branches with numbers so that instead of this (preferably in bash)

feature/myusername/ID-1111-my-branch-name
feature/myusername/ID-2222-my-branch-name
feature/myusername/ID-3333-my-branch-name
feature/myusername/ID-4444-my-branch-name

I could get a list like this (or similar)

#1 feature/myusername/ID-1111-my-branch-name
#2 feature/myusername/ID-2222-my-branch-name
#3 feature/myusername/ID-3333-my-branch-name
#4 feature/myusername/ID-4444-my-branch-name

Then checking out a branch would be as easy as

git checkout #4

Solution

  • This sounds like it would be quite easy to create. A simplistic implementation could work with two one-line scripts/aliases.

    git-lbr (list branch):

    #!/bin/bash
    
    git branch --no-color | cat -n
    

    git-coid (checkout id)

    #!/bin/bash
    
    git checkout $(git lbr | egrep "^\s+$1\s+" | egrep -o '\S*$')
    

    But that's a simplistic implementation with no error handling for cases with missing input / non-numeric input / out of range branch ids.

    Example of use:

    $ git lbr
         1    branch_42
         2    feature/super-feature
         3    foo/bar
         4  * master
    
    $ git coid 1
    Switched to branch 'branch_42'
    Your branch is up-to-date with 'master'.