Last active
August 26, 2025 14:57
-
-
Save divyanshusahu/dafcb3e0eddfb92bb3c37888737672d1 to your computer and use it in GitHub Desktop.
One command to open git repo in another branch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Add this in your .zshrc/.bashrc | |
| gt() { | |
| if [ -z "$1" ]; then | |
| echo "Usage: gt <branch_name>" | |
| return 1 | |
| fi | |
| branch="$1" | |
| repo_root=$(git rev-parse --show-toplevel 2>/dev/null) | |
| if [ -z "$repo_root" ]; then | |
| echo "❌ Not inside a git repository." | |
| return 1 | |
| fi | |
| worktree_dir="${repo_root}-${branch}" | |
| # Check if worktree already exists | |
| if [ -d "$worktree_dir" ]; then | |
| echo "✅ Worktree for '$branch' already exists: $worktree_dir" | |
| else | |
| # Try to add the branch | |
| if git show-ref --verify --quiet "refs/heads/$branch"; then | |
| echo "🌱 Adding existing branch '$branch' as worktree..." | |
| git worktree add "$worktree_dir" "$branch" | |
| else | |
| echo "✨ Branch '$branch' does not exist, creating..." | |
| git worktree add -b "$branch" "$worktree_dir" | |
| fi | |
| fi | |
| # Open in VS Code | |
| code "$worktree_dir" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment