15

我正在尝试编写一个别名来同时删除本地和远程分支,但我无法弄清楚为什么语法不起作用。在~/.gitconfig中,我尝试了以下别名,但每个都产生相同的结果,这是出乎意料的:

[alias]
     nuke = !sh -c 'git branch -D $1 && git push origin :$1'

[alias]
     nuke = !git branch -D $1 && git push origin :$1

两者都产生:

$> git branch
  * master
  mybranch
$> git nuke mybranch
Everything up-to-date
$> git branch
  * master
  mybranch

切换命令的顺序会产生不同的结果,但也不完全是我想要的:

[alias]
    nuke = !git push origin :$1 && git branch -D $1

...

$> git branch
  * master
  mybranch
$> git nuke mybranch
Everything up-to-date
Deleted branch mybranch (was d719895)
$> git branch
  * master
$> git push origin :mybranch
To git@github.com:biegel/repo.git
 - [deleted]         mybranch

当我直接在 shell 上运行该命令时,它运行良好:

$> git branch
* master
  mybranch
$> git branch -D mybranch && git push origin :mybranch
Deleted branch mybranch (was d719895
To git@github.com:biegel/repo.git
 - [deleted]         mybranch
$> git branch
* master

我尝试在~/.bashrc、 使用git push origin --delete $1和使用 shell 函数中创建别名,!f() { };但似乎没有任何效果!

我准备放弃了。关于我在这里缺少什么的任何想法?

谢谢。

4

3 回答 3

39

You can make this work just fine. You just need to add a missing '-' at the end of your definition. The '-' will signal to bash that all option processing is done, and anything that comes after becomes a parameter you can reference via $1, $2, etc:

[alias]
     nuke = !sh -c 'git branch -D $1 && git push origin :$1' -

From the command line, switch to another branch, then run the command:

git nuke branch-name

Alternately… If you are unable to add the above to your .gitconfig file for some reason, but have access to the .bashrc, .bash_profile, etc… you can add the following:

git config --global alias.nuke '!sh -c "git branch -D $1 && git push origin :$1" -'
于 2013-05-24T17:42:09.750 回答
3

If you create a bin called git-nuke and place it in a directory anywhere on your $PATH, you will achieve the same effect. The advantage with this approach is the ability to write a command with a bit more clarity and robustness.

Example, in my bash profile I have: export PATH="$HOME/.bin:$PATH".

And in ~/.bin/git-nuke, I have:

#!/bin/bash
set -eu

#
# git nuke <branch-name>
#
# Delete a branch (irrespective of its merged status) and
# remove from origin.
#

echo "Nuking $1 ..."

if git show-branch "$1" > /dev/null 2>&1
then
  git branch -D "$1"
else
  echo "No local branch to delete"
fi

git remote prune origin
if git show-branch "origin/$1" > /dev/null 2>&1
then
  echo "Deleting remote $1 ..."
  git push origin ":$1"
else
  echo "No remote branch to delete"
fi
于 2015-04-22T16:02:26.503 回答
1

You cannot use $1 in an alias. Create a script called git-nuke somewhere in your path so you have access to proper shell scripting.

You could also just install git-extras. That’s a script compilation that contains the git delete-branch script, which does exactly what you want.

于 2013-05-24T17:23:05.113 回答