In the company I work we use the gitflow workflow and in every feature branch we make sure that part of its name is the task’s id which includes a unique number. So what we end up with is something like:
What I wanted was an easy way to checkout a branch using just the number. I wanted (spoiler: and succeeded) something like this:
git ch 12345
Lets see how we can checkout a branch without an alias but by using the task’s number.
We can get the branch by listing all branches (
git branch) and then
grep for the one that contains the task’s number:
git branch | grep 12345
this will return feature/T12345-make-the-app-rock
Having a way to get the branch makes the checkout quite easy since we can use bash’s command substitution to execute the above commands and use the result directly in the checkout:
git checkout $(git branch | grep 12345)
We are now able to checkout the task’s branch but it would be nice if we could change the task’s number more easily. Lets create a function and pass the number as a parameter:
$1is where the parameter will be used (if we had more parameters we would use
$2for the second,
$3for the third etc).
- You can check the function by writing it directly in the terminal. Just make sure that you add newlines (press enter):
We can change branches easily but once we close the current terminal session we lose everything. Our goal is to have all that in a git alias.
Creating an alias can be achieved either by using
git config –global alias.ch checkout
or by doing it manually and adding the alias directly into the
.gitconfig file (usually located in the home directory). The file should end up with something like:
Having just the alias will not help us much. As is, it will work only if we give it the entire branch:
git ch feature/T12345-make-the-app-rock
What we need is a way to connect the function that we created with the alias.
The answer is provided by git itself since it has a way to create aliases that do not execute a git command but an external command:
However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a
!character. This is useful if you write your own tools that work with a Git repository.
Following the docs we can change the gitconfig file to look like this (this time the change must be made only manually because our function will need to have newlines):
What will happen when we write
git ch 12345 is:
git chwill be replaced with everything inside the
!) ending up with two commands
- the first one creates the
- the second one calls f with the parameter 12345:
And that’s it! We now have a git alias that will allow us to checkout a branch using part of its name.