基于regexp的bash alias-like命令识别

时间:2015-11-20 18:51:57

标签: bash

我怎样才能在bash中通过正则表达式解析命令,然后将其替换为预设正确的命令?

让我们说,在将回购网址粘贴到终端之前,我总是忘记输入“git clone”。

现在bash将解析任何包含字符串“git”和“@”并以“.git”结尾的命令,并在之前用添加的“git clone”替换整行。

这会使一千个命令变得更容易。任何想法?

1 个答案:

答案 0 :(得分:6)

您可以提供一个名为command_not_found_handle的函数,它可以处理尚未找到的命令。

command_not_found_handle() {
  local cmd_str

  # change the argument-list array back to a string
  printf -v cmd_str '%q ' "$@"

  # process that string:
  case $cmd_str in
    "git@"*".git") eval "git clone $cmd_str" ;;
    *) echo "No alternative for command found" >&2; return 1 ;;
  esac
}

使用case语句评估glob-style patterns而不是正则表达式;您可以启用extglob more flexible syntax来允许option,或者如果你真的那么使用一堆if [[ $str =~ $pattern ]]测试代替case真的想要正则表达式。