Skip to content
shellhacks.dev
Git

Show the repository root

Print the root of the working tree with git rev-parse --show-toplevel, from any subdirectory, and cd to it in a script that must run from the top.

1 min read
Summarize in AI

A script is started from somewhere deep in the repository and needs paths relative to the root.

Shell
git init -q demo && mkdir -p demo/src/deep && cd demo/src/deep
git rev-parse --show-toplevel
git rev-parse --show-prefix
cd "$(git rev-parse --show-toplevel)" && pwd
cd .git 2>/dev/null; git rev-parse --show-toplevel
Text
/tmp/run/S1210-1/demo
src/deep/
/tmp/run/S1210-1/demo
fatal: this operation must be run in a work tree

--show-toplevel prints the absolute path of the top level of the working tree, whichever directory inside it you stand in, and --show-prefix prints the path from there to the current directory. Both are options of git rev-parse. Using the root in cd makes a script independent of where it was launched from.

Inside the .git directory itself there is no working tree, so the last command fails with an error and prints no path. In a bare repository, the same happens. Submodules report their own root, not the parent's; use --show-superproject-working-tree to find the parent.

Share

More snippets

Git

Show the current branch name

Print the current branch name with git branch --show-current, which prints nothing on a detached HEAD, where rev-parse --abbrev-ref prints the word HEAD.

1 min read
Git

Check for uncommitted changes in a script

Test for uncommitted changes in a script with git diff --quiet, which exits 1 on a change. Add --cached for staged work, since untracked files never count.

1 min read
Git

List untracked files only

List untracked files only with git ls-files -o --exclude-standard. Without the second option the output includes every ignored build file as well.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.