Can I pass arguments to the alias of a Git command?
I have some alias in Git config, like so:
rb1 = rebase -i HEAD~1
rb2 = rebase -i HEAD~2
rb3 = rebase -i HEAD~3
rb4 = rebase -i HEAD~4
....
Is it possible to make an rb
alias so that git rb <x>
works for any <x>
?
I tried this alias:
rb = rebase -i HEAD~
but then for instance git rb 8
does not work.
Rebasing all commits since branching
If you just want to rebase all the commits that are new in your branch, since the time you branched from the parent branch, it would be easier to just have the following alias in your config:
Then, if you wanted to rebase all the commits you've added to your current branch, you could simply run:
This approach uses an argument, but instead of having to know how many commits to go back, you just supply the branch name, and it figures out most recent commit shared between the current branch and the parent branch via
git merge-base
Why this, rather than git rebase -i parentBranch
The reason you would do this rather than a straight
git rebase -i parentBranch
is that you might not want to deal with the merge-conflicts until a later point, or even deal with a merge-conflict in one commit, and then the same conflict on the same line in another commit. See https://stackoverflow.com/a/31036645/444610I wrote this function "grb" to do Git interactive rebase on a Mac, so I can say
grb 5
to show my last 5 commits:The top answer on this page does not work for me. To see my
.bash_profile
and all other Git aliases I use on my Mac:https://github.com/rayning0/bash_profile/blob/master/.bash_profile#L146
If you consider the Git Faq section "Git Aliases with argument", you could do it, but by calling git through a shell:
I haven't tested it yet, but if you can pass an argument, that would be the way to do it.
A similar solution would be to use a shell function:
@Droogans pointed out in a comment on the accepted answer that, at least on macOS (I would imagine the same will hold true for any unix-like OS, and maybe even windows), you can just use
$1
as the placeholder value representing the argument in the alias. So, to set up an alias so thatgit rb 8
becomesgit rebase -i HEAD~8
:You can also use it multiple times in an alias, so if, for example, you wanted an alias that would translate
git f my-branch
togit fetch origin my-branch:my-branch
, you can do: