Bash / zsh-Funktion, die an die Wurzel des Git-Baums cd

Nov 26 2020

Ich möchte eine Überprüfung für die Funktion erhalten, die in die Git-Baumwurzel cd oder nichts tut, wenn wir uns außerhalb des Repositorys befinden.

überprüfte 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="$(git rev-parse --show-cdup)"
    top="${top:-./}" super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then printf '%s' "$top../"
      ( cd "$top../" && git_root || return ) fi printf '%s' "$top"
  }
  local git_root
  git_root="$(git_root)" [ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}

aktualisierte 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="$(git rev-parse --show-cdup)" top="${top:-./}"
    local super_root; super_root="$(git rev-parse --show-superproject-working-tree)" if [[ "$super_root" ]]; then
      printf '%s' "$top../" ( cd "$top../" && git_root || return )
    fi
    printf '%s' "$top" } local tree_root tree_root="$(git_root)"
  [[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}

Antworten

4 chicks Nov 26 2020 at 10:12

Toll

  • Shellcheck wird zu 100% weitergegeben, was bedeutet, dass Sie alles gut zitieren, was möglicherweise problematisch sein könnte.
  • Scoping-Variablen
  • unter Verwendung der [[Bedingung für dieif
  • nette Erklärung, was es tut und warum

Könnte besser sein

  • Eine Sh-Bang-Zeile oben ist eine gute Idee für Skripte, auch wenn diese normalerweise nur während Ihrer Anmeldeskripte bezogen werden.
  • Ihre innere Funktion wird mit einer anderen Syntax definiert als Ihre äußere Funktion.
  • Sie können eine Variable in einer Zeile definieren und definieren. Zum Beispiel : local super_root="$(git rev-parse --show-superproject-working-tree)". Dies stellt sicher, dass Sie eine lokale Variable nicht definieren oder eine neue Variable nicht erfassen können. Und es wird jeweils eine Codezeile ausgeschnitten.
  • Die Wiederverwendung git_rootfür einen Variablennamen und den Funktionsnamen ist verwirrend. Ich habe mich zunächst gefragt, warum Sie versucht haben, die Funktion zu erweitern, nachdem Sie sie gerade definiert haben.
  • Verwenden Sie [[bedingt für bedingt in der letzten Zeile.