Bash/zsh function that cd to the root of git tree I'd like to get a review for the function that cd into the git tree root or does nothing if we are outside of the repository.
reviewed version:
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  git_root() {
    local super_root
    local top
    top=&quot;$(git rev-parse --show-cdup)&quot;
    top=&quot;${top:-./}&quot;
    super_root=&quot;$(git rev-parse --show-superproject-working-tree)&quot;
    if [[ &quot;$super_root&quot; ]]; then
      printf '%s' &quot;$top../&quot;
      ( cd &quot;$top../&quot; &amp;&amp; git_root || return )
    fi
    printf '%s' &quot;$top&quot;
  }
  local git_root
  git_root=&quot;$(git_root)&quot;
  [ &quot;x${git_root}&quot; != &quot;x./&quot; ] &amp;&amp; cd &quot;$(git_root)&quot; &amp;&amp; return || return 0
}

updated version:
#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  function git_root {
    local top; top=&quot;$(git rev-parse --show-cdup)&quot;
    top=&quot;${top:-./}&quot;
    local super_root; super_root=&quot;$(git rev-parse --show-superproject-working-tree)&quot;
    if [[ &quot;$super_root&quot; ]]; then
      printf '%s' &quot;$top../&quot;
      ( cd &quot;$top../&quot; &amp;&amp; git_root || return )
    fi
    printf '%s' &quot;$top&quot;
  }
  local tree_root
  tree_root=&quot;$(git_root)&quot;
  [[ &quot;x${tree_root}&quot; != &quot;x./&quot; ]] &amp;&amp; cd &quot;${tree_root}&quot; &amp;&amp; return || return 0
}
Great

100% pass on shellcheck which means you're doing great with quoting everything that could be potentially problematic.
scoping variables
using [[ conditional for the if
nice explanation of what it is doing and why

Could be better

a sh-bang line at the top is a good idea for scripts, even if this would usually just be sourced during your login scripts.
Your inner function is defined with different syntax than your outer function.
You can scope and define a variable in one line.  For example: local super_root=&quot;$(git rev-parse --show-superproject-working-tree)&quot;.  This makes sure you don't fail to define a local variable or fail to scope a new variable.  And it cuts out a line of code in each case.
Reusing git_root for a variable name and the function name is confusing.  I initially wondered why you were trying to scope the function after you had just defined it.
use [[ conditional for conditional in the last line.