最灵活的方法是使用自定义 Git 命令。例如,在您的$PATH
中的某个位置创建以下 Python 脚本,命名为git-rmbranch
并使其可执行:
import argparse
import subprocess
import sys
def rmbranch(branch_name, remote, force):
try:
print(subprocess.run(['git', 'branch', '-D' if force else '-d', branch_name],
capture_output=True, check=True, encoding='utf-8').stdout, end='')
except subprocess.CalledProcessError as exc:
print(exc.stderr.replace(f'git branch -D {branch_name}', f'git rmbranch -f {branch_name}'), end='')
return exc.returncode
return subprocess.run(['git', 'push', remote, '--delete', branch_name]).returncode
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Delete a Git branch locally and remotely.')
parser.add_argument('-r', '--remote', default='origin', help="The remote name (defaults to 'origin')")
parser.add_argument('-f', '--force', action='store_true', help='Force deletion of not fully merged branches')
parser.add_argument('branch_name', help='The branch name')
args = parser.parse_args()
sys.exit(rmbranch(args.branch_name, args.remote, args.force))
然后,git rmbranch -h
将向您显示使用信息:
usage: git-rmbranch [-h] [-r REMOTE] [-f] branch_name
Delete a Git branch locally and remotely.
positional arguments:
branch_name The branch name
optional arguments:
-h, --help show this help message and exit
-r REMOTE, --remote REMOTE
The remote name (defaults to 'origin')
-f, --force Force deletion of not fully merged branches
请注意,
git push origin --delete <branch_name>
命令也会删除本地的远程跟踪分支(默认情况下是
origin/<branch_name>
),因此无需担心。
附注:您可以在
这里找到此 Git 命令的最新版本。欢迎评论和建议。
deleted remote-tracking branch
**”:请参见 https://github.com/git/git/commit/ccd593cffaa020ff767860ec211462b8dbd727a6#diff-d18f86ea14e2f1e5bff391b2e54438cbR268 - VonC