Git: Output the top-level directory of the current repository

Pull me up to the top level!

To output the root directory of the current repository, use:

$ git rev-parse --show-toplevel
/Users/hacker/Projects/smurfables

This option outputs the absolute path regardless of where you are within the current repository.

To output it as a relative path from the current directory, add --path-format=relative:

$ git rev-parse --path-format=relative --show-toplevel
../../

The --show-toplevel option was added in Git 1.7.0 (2010-02-12), thanks to Steven Drake in commit 7cceca5cccd.

Within alternative working trees

It’s possible for a repository to have multiple working trees, created with the git worktree command:

$ git worktree add ../smurfables-testing
Preparing worktree (new branch 'smurfables-testing')
HEAD is now at 60786a5 Smurfish smurfalator

git rev-parse --show-toplevel outputs the top-level of the current working tree:

$ cd ../smurfables-testing

$ git rev-parse --show-toplevel
/Users/hacker/Projects/smurfables-testing

To get the top-level directories of all working trees, use git worktree list with its --porcelain option and -z for null-byte-delimited strings (in case any directory name contains a newline). You’ll need to then parse the output to split by the null byte and select from each line starting with “worktree“. Here’s what the command output looks like, excluding -z because that doesn’t display correctly on the terminal:

$ git worktree list --porcelain
worktree /Users/hacker/Projects/smurfables
HEAD 60786a509fbb23dfca8808bf659304d349989b9d
branch refs/heads/main

worktree /Users/hacker/Projects/smurfables-testing
HEAD 60786a509fbb23dfca8808bf659304d349989b9d
branch refs/heads/smurfables-testing

Fin

May you always remember your roots,

—Adam


Read my book Boost Your Git DX for many more Git lessons.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: