Git / Create And Switch To New Branch Based On Commit
Create And Switch To New Branch Based On Commit
Creates a new branch from a specific commit and checks it out.
git switch -c <branch_name> <commit> git switch -c <branch_name> <commit> #!/bin/bash
# Create And Switch To New Branch Based On Commit
git switch {{[-c|--create]}} {{branch_name}} {{commit}} import subprocess
# Create And Switch To New Branch Based On Commit
# Make sure to replace <placeholders> with actual values
def run_command():
cmd = [
"git",
"switch",
"-c",
"<branch_name>",
"<commit>"
]
try:
print(f"Executing: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
except FileNotFoundError:
print("Error: git not found. Please install it first.")
if __name__ == "__main__":
run_command() When To Use
Validating features or hotfixes from a commit that is not the HEAD.
Pro Tip
Utilize 'git log' in a separate terminal to find stable commits before branching off.
Command Builder
Tune the command before you copy it
git switch -c <branch_name> <commit> Anatomy of Output
Understanding the result
Switched to a new branch 'fix-issue-123' Branch Status Indicates successful creation and switch.
Your branch is based on '6a1c7d4'. Base Commit Confirmation Verifies the new branch is set at the specified commit.
A new branch has been created: 'fix-issue-123'. Branch Creation Notification Confirms that the new branch was successfully created.
Power User Variants
Optimized versions
git switch -c branch_name commit --track upstream/branch_name Create tracking branch based on commit from upstream.
git switch -b branch_name commit --no-ff Create a new branch preventing fast-forward merges.
Troubleshooting
Common pitfalls
fatal: A branch named 'fix-issue-123' already exists.
Solution: Switch to the existing branch using 'git switch fix-issue-123'.
fatal: Invalid object name '6a1c7d4'.
Solution: Confirm the commit hash is accurate and exists.
fatal: cannot switch branches: your index contains uncommitted changes.
Solution: Commit or stash any changes before switching branches.
Command Breakdown
What each part is doing
-
git - Base Command
- The executable that performs this operation. Here it runs Git before the shell applies any redirect operators.
-
-c - c| create
- The value supplied for c| create.
-
<branch_name> - branch name
- The value supplied for branch name.
-
<commit> - commit
- The value supplied for commit.
-
-c - Command Option
- Tool-specific option used by this command invocation.
Alternative Approaches
Comparable commands in other tools
Alternative version control tools for the same job.
jj split -r <revision> -d <revset> Jj / Split Revision Insert Before After jj split -r <revision> -B <revset> -A <revset> Bd / Sync Changes And Import From Git bd sync Fossil / Pull Remote Changes Into Local fossil pull <remote_url> Jj / Update Revision Description jj desc -m "<message>" -r <revsets>