Bash 正则表达式与命令行不匹配

问题描述

如何让 git commit 调用我编写的自定义包装器 shellscript(例如 ~/.gitcommit),但所有其他 git 命令只是像往常一样传递给 git。>

我正在尝试 https://superuser.com/a/175802/325613

指出的
preexec () {
  echo preexecing "$1"
  if [[ "$1" =~ ^[:space:]*git[:space:]+commit[:space:].* ]]; then
    echo git commit detected
  fi
}

preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # don't cause a preexec for $PROMPT_COMMAND
    local this_command=`HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"`;
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG

但是这个打印是这样的

$ git commit
preexecing git commit
fatal: not a git repository (or any of the parent directories): .git
$ git commit with some args
preexecing git commit with some args
fatal: not a git repository (or any of the parent directories): .git
$          git commit Now Now Now
preexecing git commit Now Now Now
fatal: not a git repository (or any of the parent directories): .git
$ git       commit        space
preexecing git       commit        space
fatal: not a git repository (or any of the parent directories): .git

似乎我的正则表达式永远不会匹配。为什么?

解决方法

您的正则表达式不匹配,因为 [:space:][aceps:] 相同;与 aceps: 中的一个相匹配的字符类.你可能是说[[:space:]]。以下应该工作

if [[ "$1" =~ ^[[:space:]]*git[[:space:]]+commit[[:space:]] ]]

但是,您当前的方法有点奇怪。您是否考虑过编写pre-commit git hook

即使你有一个非常罕见的情况,git hook 不是一个选项,那么 bash 函数会更好:

git() {
  if [ "$1" = commit ]; then
     # do stuff,e.g. insert arguments using `set --`
  else
    # in every case,run the real git
    command git "$@"
  fi
}