Jordan Barrett
Jordan Barrett

Reputation: 1017

How to find the worktree path of a branch

Let's say I'm inside a Git repo with worktrees. Given a branch name, how can I find out if this branch is checked out in a worktree, and if so, the path to this worktree?

P.S. this is for a script, I know I could parse the output of git worktree list, but I'd prefer a solution using git rev-parse or similar.

Upvotes: 0

Views: 87

Answers (1)

Guildenstern
Guildenstern

Reputation: 3841

Based on the hints from commenters joanis and LeGEC:

#!/bin/sh

set -u
branch="$1"
git check-ref-format --branch "$branch" >/dev/null || exit 1
git worktree list --porcelain \
    | grep  "^branch refs/heads/$branch" >/dev/null \
    || exit 1
git worktree list --porcelain \
    | grep -B2 "^branch refs/heads/$branchName" \
    | head -1 | cut -d' ' -f 2

Upvotes: 0

Related Questions