linux - command_not_found_handler 不带斜杠

标签 linux bash

我在 bash shell(Ubuntu 16 中的 4.3 版)中使用 "/" 登录时遇到问题。我有一个功能:

command_not_found_handler() {
  if [[ "$1" =~ any$ ]]; then
    echo "$1"
  fi
}

当此命令以any结尾时,此函数应写回终端中写入的任何命令的内容。

这很好用,除非我用 / 写东西,比如 whatever/any。在那种情况下,我会收到类似于以下内容的错误:

bash: no such file or directory: whatever/any

任何尝试在函数中转义此 / 都没有效果(例如 if [[ "$1"=~/any$ ]]; thenif [[ "$1"=~\/any$ ]]; then).

我该怎么做才能让它与 / 符号一起工作?

最佳答案

command_not_found_handle(无尾随 r)仅在通过 PATH 搜索给定命令后调用。

当用户将显式路径传递给命令时,不会发生此类搜索,这就是解释包含 / 的任何内容的方式。


引用the relevant documentation , 并强调:

  1. If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files to avoid multiple PATH searches (see the description of hash in Bourne Shell Builtins). A full search of the directories in $PATH is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle. If that function exists, it is invoked with the original command and the original command’s arguments as its arguments, and the function’s exit status becomes the exit status of the shell. If that function is not defined, the shell prints an error message and returns an exit status of 127.

文档的整个段落仅与开头列出的条件集相关:命令不能是 shell 函数,不能是内置函数,也不能包含斜线。

关于linux - command_not_found_handler 不带斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130133/

相关文章:

linux - Linux bash shell 注入(inject)命令的可能列表是什么?

c - 我的 realloc 函数返回段错误

linux - 自动打开和关闭vlc播放器

linux - 将 Bash 参数传递给封装 AWK 命令的 Bash 变量

bash - bash 中的一行 if 语句

linux - Team City“最小构建代理” Docker镜像-“npm:未找到” Linux问题?

linux - valgrind vgdb 与 emacs 中的 gdb

ruby - 为什么我不能在 Ruby 脚本中访问我的 bash 提示符?

linux - 带有反引号的变量内部的bash转义感叹号

linux - 如何避免 Windows 上 Git/IntelliJ 中文件中的 CR?