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

Bash regex doesn't match command line

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

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

指出的
preexec () {
  echo preexecing ""
  if [[ "" =~ ^[: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 中的 一个 的字符 class , 或 :。您的意思可能是 [[:space:]]。以下应该有效

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

不过,你现在的做法有点奇怪。你考虑过写一个pre-commit git hook吗?

即使在非常罕见的情况下,git 钩子不是一个选项,那么 bash 函数会更好:

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