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.
A script is started from somewhere deep in the repository and needs paths relative to the root.
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/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.