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
  • [About `echo $(…)`](https://superuser.com/q/1352850/432690). – Kamil Maciorowski Dec 23 '20 at 18:17
  • @KamilMaciorowski, I could use something like `MY_BRANCH=$(git branch | sed "s|[* ]||g;$1q;d");git checkout "$MY_BRANCH"`, but still, how do I pass an arg to it? Look at "Expected behaviour" in my question – Alex Kosh Dec 23 '20 at 18:22
  • @KamilMaciorowski, I don't want it to be a function, it should be a git alias placed inside .gitconfig. It's possible to execute commands from there, so I need some kind of wrapping for existing code to substitute '$1' to passed arg – Alex Kosh Dec 23 '20 at 18:24
  • I know how to do this with function, but want it to be oneliner – Alex Kosh Dec 23 '20 at 18:25

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