sh = "!f() { root=$(pwd)/ && cd ${root%%/.git/*} && git rev-parse && exec \"$@\"; }; f"
这可以让你轻松地做git sh ag <string>这样的事情
支持不同命名或外部.git或$GIT_DIR目录的强大解决方案。
请注意,$GIT_DIR可能指向外部的某个地方(而不是被称为.git),因此需要进一步检查。
把这个放在你的.bashrc:
# Print the name of the git working tree's root directoryfunction git_root() {local root first_commit# git displays its own error if not in a repositoryroot=$(git rev-parse --show-toplevel) || returnif [[ -n $root ]]; thenecho $rootreturnelif [[ $(git rev-parse --is-inside-git-dir) = true ]]; then# We're inside the .git directory# Store the commit id of the first commit to compare later# It's possible that $GIT_DIR points somewhere not inside the repofirst_commit=$(git rev-list --parents HEAD | tail -1) ||echo "$0: Can't get initial commit" 2>&1 && false && returnroot=$(git rev-parse --git-dir)/.. &&# subshell so we don't change the user's working directory( cd "$root" &&if [[ $(git rev-list --parents HEAD | tail -1) = $first_commit ]]; thenpwdelseecho "$FUNCNAME: git directory is not inside its repository" 2>&1falsefi)elseecho "$FUNCNAME: Can't determine repository root" 2>&1falsefi}
# Change working directory to git repository rootfunction cd_git_root() {local rootroot=$(git_root) || return 1 # git_root will print any errorscd "$root"}
#$1: Path to child directorygit_root_recurse_parent() {# Check if cwd is a git root directoryif [ -d .git/objects -a -d .git/refs -a -f .git/HEAD ] ; thenpwdreturn 0fi
# Check if recursion should end (typically if cwd is /)if [ "${1}" = "$(pwd)" ] ; thenreturn 1fi
# Check parent directory in the same waylocal cwd=$(pwd)cd ..git_root_recurse_parent "${cwd}"}
git_root_recurse_parent