3

I have a repository with a number of branches b1-long-name, b2-long-name, b3-too-long-name

I want to be able to switch between branches fast. Also I want to run additional git command before I switch the branch.

I trying to approach that with a bash script, here is my custom script gitSwitch.sh

#!/bin/sh

set -e

git reset #<-- additional command
git checkout -f b2-long-name

But the problem here I have to create a script per branch that I do not really want, I wonder how would you pass a param to the script so it will use a proper branch name?

gitSwitch b1 -> would checkout b1-long-name
gitSwitch b2 -> would checkout b2-long-name
and so on

Any ideas how to approach it best?

oguz ismail
  • 39,105
  • 12
  • 41
  • 62
sreginogemoh
  • 9,074
  • 25
  • 83
  • 142

3 Answers3

3

Any ideas how to approach it best?

For starters, install a git completion script so that you can type something like git checkout b1<tab> instead of the complete long name. You can also make some shorter aliases for often used commands.

Caleb
  • 122,179
  • 19
  • 178
  • 268
  • 1
    Completion scripts are probably the way to go here. I've never been satisfied with any of them myself though, as they make assumptions I disagree with. Fortunately the new `git restore` is likely to help here as a completer for `git restore` won't assume "branch" when I mean "file name" :-) – torek Apr 28 '20 at 06:02
  • Thanks for an answer, I also want to script the additional command that actually much longer than `git reset` to execute before each `git checkout` – sreginogemoh Apr 28 '20 at 09:39
1

You can use git branch --list pattern and store it in an array

In your case:

readarray -d '' branches < <(git branch --list "*$1*")
len=${#branches[@]}

If that array has only one element, then whatever you passed to your script is specific enough to isolate only one branch and you can switch to it.

If you have only one branch starting with b1, you can use b1 as a parameter.

Obviously, using git checkout -f "$1-long-name" would not work since the suffix "long-name" varies between different branches.

Community
  • 1
  • 1
VonC
  • 1,129,465
  • 480
  • 4,036
  • 4,755
  • OK, i see, how then you call that script? – sreginogemoh Apr 28 '20 at 09:44
  • 1
    @sreginogemoh `gitSwitch b1` for instance: you pass as a parameter any part of a branch name, specific enough to select only *one* branch (if you find more than one branch, your script should fail in error) – VonC Apr 28 '20 at 09:47
0

You can create a git alias which would execute additionals commands.

# .git/config
[alias]
    sw = !git reset && git checkout $1 && :

To avoid typing long names, you could use tab completion.

git sw b1<tab>

If tab completion is not working, you might need configure it first. See the following:

How to configure git bash command line completion?

sergej
  • 15,727
  • 6
  • 44
  • 82