• 2007-05-05

    神奇的命令行:找不到命令(command not found) - [LBE]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://gosman.blogbus.com/logs/5263038.html

    原文:CLI Magic: command not found, suggest what to apt-get
    作者:mysurface
    译者:gosman(lianmingchang2008#gmail.com)
    来自:http://gosman.blogbus.com
    版本:V 1.1.0
    时间:2007-9-7

    最近我从 Ubuntu Edgy 升级到 Ubuntu Feisty,发现 Feisty 一个有趣的程序 command-not-found。当你输入系统中不存在的命令时,该程序就会提示包含该命令的安装包并提示用 apt-get 安装。

    以未安装的命令 trafshow 为例,输出为:

    The program 'trafshow' is currently not installed. You can install it by typing:
    sudo apt-get install netdiag
    Make sure you have the 'universe' component enabled
    bash: trafshow:找不到命令
    

    如果不行的话,请去掉 /etc/bash.bashrc 中以下语句的注释:

    # if the command-not-found package is installed, use it
    if [ -x /usr/bin/command-not-found ]; then
    function command_not_found_handle {
    /usr/bin/command-not-found $1
    return $?
    }
    fi
    

    command-not-found 命令是能返回提示语句的 Python 脚本。因此只要输入command-not-found <command name>就会输出提示语句,不管该命令安装与否。

    command-not-found gedit
    The program 'gedit' is currently not installed. You can install it by typing:
    sudo apt-get install gedit
    

    我们可以用 command-not-found 查找包含特定命令的安装包,与可以完成同样操作的dpkg -S相比,command-not-found查询更迅速。

    还可以在 bash 脚本中使用 command-not-found 命令。看下面这个简单脚本:

    #!/bin/bash
    Cmd=`which trafshow`;
    if [ -n $Cmd ]
    then
    command-not-found trafshow
    fi
    

    以上脚本查找 trafshow 的绝对路径,如果 tarfshow 没有安装,变量 Cmd 是个空值(null)就会返回 command-not-found 的提示语句。这样做的原因是在 bash 脚本中不会自动使用 command-not-found 特性。我的意思是在 bash 脚本中使用未安装的命令,不会输出 command-not-found 的提示语句。

    我不知道除了 Ubuntu Feisty 在别的发行版本中是否有 command-not-found,从Agile Testing那里知道可以在 Ubuntu Edgy中用 apt-get 安装 command-not-found。

    command-not-found 特性会减慢命令行的处理,因为每次输入未安装的命令时就会执行查找工作。Niath对 command-not-found 执行时间进行测试,结果是我们能接受的。


    收藏到:Del.icio.us