How to Create a Git Branch if it Doesn't Exist in Python

Utility script that checks if a Git branch exists locally and either creates it or checks it out, with error handling.

Easy Python 3.9+ Aug 9, 2026 Git + Python 12 views 0 copies

Python code

36 lines
Python 3.9+
import subprocess
import sys

def ensure_branch(branch_name):
    """Create a Git branch if it doesn't exist, otherwise checkout it."""
    try:
        # Check if the branch exists locally
        result = subprocess.run(
            ["git", "branch", "--list", branch_name],
            capture_output=True,
            text=True,
            check=True
        )
        
        if not result.stdout.strip():
            # Branch doesn't exist — create and switch to it
            subprocess.run(
                ["git", "checkout", "-b", branch_name],
                check=True
            )
            action = "created"
        else:
            # Branch exists — switch to it
            subprocess.run(
                ["git", "checkout", branch_name],
                check=True
            )
            action = "switched to existing"
        
        return f"Branch '{branch_name}' {action} successfully"
    except subprocess.CalledProcessError as e:
        return f"Error: {e}"

if __name__ == "__main__":
    branch = "feature/mock-implementation"
    print(ensure_branch(branch))

Output

stdout
Branch 'feature/mock-implementation' created successfully

How it works

The code runs git branch --list first to check if the branch already exists locally. If the output is empty the branch doesn't exist, so it creates and checks out the branch with git checkout -b. Otherwise it just checks out the existing branch with git checkout. The capture_output=True and text=True parameters capture the command output as text, letting the script inspect it programmatically. Wrapping subprocess calls in a try/except converts Git errors into readable CalledProcessError messages.

Common mistakes

  • Checking `result.stdout` directly fails when shell redirection is involved — always use `.strip()`
  • Forgetting `check=True` means Git failure messages are silently ignored
  • Confusing local branches with remote branches — `--list` only checks local branches

Variations

  1. Use `git rev-parse --verify` for a faster existence check that raises on failure
  2. Call `git switch -c` instead of `git checkout -b` for newer Git versions

Real-world use cases

  • Bootstrapping CI/CD jobs where ephemeral feature branches may or may not exist yet.
  • Automating branch creation in setup scripts when on-boarding new developers.
  • Synchronizing local environments with remote branches in team workflows.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.