在执行任何 cd 命令后运行 git fetch

nor*_*ter 2 bash zsh git cd-command

我需要在后台执行任何 cd 命令之后运行 git fetch,并且仅当我位于 git 目录中时。

Gil*_*il' 5

这分为三个部分:

  1. 运行一些代码来更改当前目录。在 zsh 中,您可以将此代码放入函数中chpwd或者将其放入数组中具有不同名称的函数中chpwd_functions示例)。请参阅进入目录时执行 bash 脚本以了解 bash 实现。
  2. 检测 git 工作副本。由于您只对 git 感兴趣,因此您可以运行git rev-parse --show-toplevel. 如果您对其他版本控制系统感兴趣,还有更高级的框架可以检测版本控制。
  3. 跑步git fetch

这是更改为 git 存储库时chpwd运行的实现。git fetch

chpwd () {
  set -- "$(git rev-parse --show-toplevel 2>/dev/null)"
  # If cd'ing into a git working copy and not within the same working copy
  if [ -n "$1" ] && [ "$1" != "$vc_root" ]; then
    vc_root="$1"
    git fetch
  fi
}
chpwd
Run Code Online (Sandbox Code Playgroud)

此代码位于您的 shell 启动脚本中:.zshrc对于 zsh,.bashrc对于 bash(在 bash 中,您还需要包装器来调用chpwd目录更改)。