How to find the main worktree from any worktree

Viewed 127

Is there a way to determine the "main" worktree (i.e. the one with a .git directory) by running a command in any worktree? This does not work:

git rev-parse --show-toplevel

The best I can think of is parsing git worktree list --porcelain, and then testing if there is a .git directory in each one. That seems a bit naff though. Does Git have a built in command to do this?

2 Answers

Aha! It seems you can do

git rev-parse --path-format=absolute --git-common-dir

and then either just remove the .git from the path (probably safe) or do

git rev-parse --path-format=absolute --show-toplevel

in the directory returned from the first path.

--path-format=absolute is helpful because otherwise these commands sometimes return relative paths and sometimes absolute paths.

The comments on this answer helped me figure this out.

I dont know of a command, doing what you want, but you could parse the contents of the ".git"-File in your Worktree

Related