【问题标题】:command_not_found_handler not working in maccommand_not_found_handler 在 mac 中不起作用
【发布时间】:2015-02-17 18:51:09
【问题描述】:

所以我的 .bashrc 文件中有这个 bash 代码...我使用的是 Mac OS X Yosemite

command_not_found_handle () 
{ 
    runcnf=1;
    retval=127;
    [ ! -S /var/run/dbus/system_bus_socket ] && runcnf=0;
    [ ! -x /usr/libexec/packagekitd ] && runcnf=0;
    if [ $runcnf -eq 1 ]; then
        /usr/libexec/pk-command-not-found $@;
        retval=$?;
    else
        echo "lalalla";
        retval=1;
    fi;
    return $retval
}

我之前在 linux 环境中使用过这段代码,它工作得很好......当用户输入一个不存在的 bash 命令时,它会默认通过回显“lalalal”......但是当我在我的 Mac OS X Yosemite 上使用它,尽管我的 .bashrc 文件已正确注册(我已执行 source ~/.bash_profile 并且我的 .bash_profile 包含代码 source ~/.bashrc

我的 .bashrc 中存在的其他命令执行得很好......

我做错了什么?当用户输入 mac 中不存在的命令时,如何让 mac 使用 command_not_found_handle?

更新

@tristan 所以我通过 brew 升级了 bash,当我运行 bash --version 输出时得到确认

GNU bash, version 4.3.30(1)-release (x86_64-apple-darwin14.0.0)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

此外,我重做了源 .bash_profile

但是当我输入一个不存在的命令时它仍然显示

-bash: askldfasf: command not found

我做错了什么?

【问题讨论】:

  • 次要备注:return $retval 错误:return 只返回数字参数。

标签: linux macos bash shell command-line


【解决方案1】:

command_not_found_handle 被引入到 Bash 版本 4。

OS X Yosemite 默认附带 bash-3.2。

为了介绍这个,您可以检查每个命令的退出代码以查找退出代码 127(“找不到命令”)并在之后附加对该函数的调用。您可以通过检查先前命令的退出代码为 127 并调用您的自定义 command_not_found_handle 函数(使用 $? 和 PROMPT_COMMAND)自行修补此行为。

也就是说,如果我站在你的立场上,我可能会通过homebrewbrew install bashsource 安装它来升级 Bash。

例如

bash-4.3$ cat not_found.bash
command_not_found_handle()
{
        echo ":("
}
bash-4.3$ source not_found.bash
bash-4.3$ a
:(

我测试了你的脚本,因为它目前也在我的机器上:

bash-4.3$ source pillar.bash
bash-4.3$ a
lalalla

以交互方式测试source-ing 您的脚本,以确保它在您的机器上是相同的。

【讨论】:

  • 是否可以升级到 bash 版本 4?此外,是否有可以执行相同操作的 command_not_found_handle 的替代方法?
  • @pillarOfLight 现在将其添加到我的答案中。你有选择:)
猜你喜欢
  • 2014-01-29
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
相关资源
最近更新 更多