brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: git rev-parse --show-toplevel prints the root folder of your repository

Git
~/tips/tip-git-rev-parse-show-toplevel

git rev-parse --show-toplevel

Prints the absolute path of the top folder of the current Git repository, from any subfolder.

I like scripts that work no matter which folder I start them from. In a Git project that means one question comes up all the time: where is the root? Counting ../../.. is a bad answer. Git can tell you.

git rev-parse --show-toplevel

Run it anywhere inside a repository and it prints the absolute path of the folder that holds the .git directory, for example /home/me/projects/blog. Nothing else is printed, so you can use it directly in a script.

cd "$(git rev-parse --show-toplevel)"
ls package.json

That jumps to the root of the repository, however deep you were. I’d put the quotes around it every time, because a path with a space in it breaks the command otherwise.

It is also handy in a Git alias or a hook. Hooks can start in odd places, and this gives you a fixed starting point without hard-coding a path.

One caveat: outside a repository the command fails with fatal: not a git repository and a non-zero exit code. In a script, check the exit code before you cd into an empty result, because cd "" quietly stays where you are. Inside a submodule you get the root of the submodule, not of the parent project. For that, Git has the separate option --show-superproject-working-tree.

Further reading: git-rev-parse documentation

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link