Last active
October 10, 2025 20:20
-
-
Save raygesualdo/5ac9d9d45b51a65ec1f243aeda96c909 to your computer and use it in GitHub Desktop.
Shell function for creating git worktrees
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
| # Fn to pull git branch from remote when not checked out | |
| pull_branch() { | |
| branch=${1:-main} | |
| git fetch origin "$branch":"$branch" | |
| } | |
| # Fn to create git worktrees quickly | |
| # | |
| # It accepts three parameters: | |
| # - A branch name to create the worktree for (required) | |
| # - An adjacent directory to create the worktree in; defaults to the current directory name with `-temp` appended (optional) | |
| # - A base branch to use when branching; defaults to `main` | |
| # | |
| # Usage: | |
| # wc new-feature-branch new-feature development | |
| # wc hotfix-a | |
| wt() { | |
| skip_vscode=0 | |
| for arg do | |
| shift | |
| if [ "$arg" = "--no-code" ]; then | |
| skip_vscode=1 | |
| continue | |
| fi | |
| set -- "$@" "$arg" | |
| done | |
| branch_name="$1" | |
| worktree_path_fallback="`basename $PWD`-temp" | |
| worktree_path="../${2:-$worktree_path_fallback}" | |
| base_branch="${3:-main}" | |
| if [ -z "$branch_name" ]; then | |
| echo "No branch name provided. Exiting..." | |
| `exit 1`; | |
| return; | |
| fi | |
| # If the branch already exists, make it the base and don't provide a branch name | |
| if [ -n "`git branch | grep "$branch_name"`" ]; then | |
| git worktree add "${worktree_path}" "${branch_name}" | |
| else | |
| [ `git branch --show-current` != "$base_branch" ] && pull_branch "$base_branch" | |
| git worktree add "${worktree_path}" -b "${branch_name}" "${base_branch}" | |
| fi | |
| if [ $skip_vscode -eq 0 ]; then | |
| code "${worktree_path}" | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment