The most flexible way is to use a custom Git command. For example, create the following Python script somewhere in your $PATH
under the name git-rmbranch
and make it executable:
#!/usr/bin/env python3
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))
Then git rmbranch -h
will show you usage information:
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
Note that git push origin --delete <branch_name>
also removes the local remote-tracking branch (origin/<branch_name>
by default), so no need to care about that.
P.S. You can find the latest version of this Git command here. Comments and suggestions are welcome.
deleted remote-tracking branch
": see github.com/git/git/commit/… – VonC May 25 '15 at 14:57