1

I want to change git branches by it's number

To show branches numbers I use this (with alias):

$ git br | nl
     1  * master
     2    test

Now I want to get branch name by it's number and pass it to git checkout:

echo $(git branch | sed "s|[* ]||g;$1q;d") | xargs git checkout

But how to pass '$1' from args to this command, supposing it have an alias?

Expected behaviour:

alias checkout='echo $(git branch | sed "s|[* ]||g;$1q;d") | xargs git checkout'
checkout 2 # checkout to branch test
Alex Kosh
  • 121
  • 4

1 Answers1

1

I found a solution by myself with help of this blog post

I wrapped my previous code with function and place in inside an alias, so my .gitconfig looks like:

[alias]
  br = "!git branch | nl"
  chbr = "!f() { MY_BRANCH=$(git branch | sed \"s|[* ]||g;$1q;d\"); git checkout $MY_BRANCH; }; f"

And now I can do things like:

$ git br
     1  * master
     2    test

$ git chbr 2 Switched to branch 'test'

Alex Kosh
  • 121
  • 4