3

I regularly have to delete a local and remote Git branch. Therefore, I run the following commands:

$ git branch -d feature-branch
$ git push --delete origin feature-branch

Since I mostly execute these two commands in a row, I would like to create an alias for them. Here is my approach:

alias gpdo='git branch -d $1 && git push --delete origin $1

However, this fails with the following error:

fatal: branch name required

0

1 Answer 1

8

When you want aliases to have parameters you can use functions, e.g.

$ gpdo () {
    git branch -d "$1" && git push --delete origin "$1"
}

Then you can do gpdo branch_name

This is also useful for multiple commands although they can also be done with an alias with multiple &&s if there are no parameters and no conditional logic, looping, etc. however when parameters are needed I switch to using functions

Git itself also allows aliases, for example see:

You may also find Git alias multi-commands with ; and && helpful

5
  • I tested your function. Only the second command is executed.
    – JJD
    Commented Dec 9, 2015 at 11:27
  • Sorry again - but the solution does not work for me.
    – JJD
    Commented Jan 20, 2016 at 15:58
  • 2
    @JJD: This solution is clearly correct, given the question. You will need to provide a better diagnosis than "doesn't work" if you want help. For instance, are you certain that your supplied commands are correct? I have corrected the minor discrepancies between your question and this answer; you might want to retry the solution as I've edited it. Commented Feb 10, 2016 at 2:30
  • @JJD, shooting in the dark here: If the branch you are trying to delete is currently checked out, git won't let you delete it. (But even then there is no way that the shell can execute only the right side of a dual command connected with &&. You are simply mistaken.)
    – Wildcard
    Commented Feb 10, 2016 at 3:58
  • 1
    @WarrenYoung Finally, you nudged my nose into the dirt again. I had an alias configured somewhere else which overwrote the function. In short, the function by Michael works - thanks! One issue (worth a new question) is that there is no auto-completion for branch names when I use the function within zsh.
    – JJD
    Commented Feb 11, 2016 at 13:06

Not the answer you're looking for? Browse other questions tagged .