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.
Python code
36 linesimport 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
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
- Use `git rev-parse --verify` for a faster existence check that raises on failure
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.