Pass an argument to a Git alias command

Viewed 24655

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.

4 Answers

I wrote this function "grb" to do Git interactive rebase on a Mac, so I can say grb 5 to show my last 5 commits:

function grb {
  git rebase -i HEAD~$1
}

The top answer on this page does not work for me. To see my .zprofile and all other Git aliases I use on my Mac:

https://github.com/rayning0/zsh_profile/blob/master/.zprofile#L157

@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 that git rb 8 becomes git rebase -i HEAD~8:

    rb = "!git rebase -i HEAD~$1;"

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 to git fetch origin my-branch:my-branch, you can do:

    f = "!git fetch origin $1:$1"
Related